irwan

PHP - Insert Image to Database

Nov 12th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. CREATE TABLE pics (
  2.  row_id  INT           NOT NULL AUTO_INCREMENT PRIMARY KEY,
  3.  name   VARCHAR(30)  NOT NULL,
  4.  size     INT          NOT NULL,
  5.  type    VARCHAR(10) NOT NULL,
  6.  content BLOB          NOT NULL
  7. )
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14. <?php
  15. // Connect to database
  16.  
  17. // Make a MySQL Connection
  18.   mysql_connect("localhost","root","") or die(mysql_error());
  19.   mysql_select_db("test") or die(mysql_error());
  20.  
  21. // Insert any new image into database
  22.  
  23. if(isset($_POST['xsubmit']) && $_FILES['imagefile']['name'] != "") {
  24.   $fileName = $_FILES['imagefile']['name'];
  25.   $fileSize = $_FILES['imagefile']['size'];
  26.   $fileType = $_FILES['imagefile']['type'];
  27.   $content  = addslashes (file_get_contents($_FILES['imagefile']['tmp_name']));
  28.  
  29.   if(!get_magic_quotes_gpc()) {
  30.     $fileName = addslashes($fileName);
  31.   }
  32.  
  33.   // Checking file size
  34.   if ($fileSize < 150000) {
  35.     mysql_query ("insert into pics (name,size,type,content) "
  36.    . "values ('$fileName','$fileSize','$fileType','$content')");
  37.   } else {
  38.     $err = "Too large!";
  39.   }
  40. }
  41.  
  42. // Find out about latest image
  43.  
  44. $gotten = mysql_query("select * from pics order by row_id desc");
  45. $row    = mysql_fetch_assoc($gotten);
  46. $bytes  = $row['content'];
  47.  
  48. // If this is the image request, send out the image
  49.  
  50.  if ($_REQUEST['pic'] == 1) {
  51.    header("Content-type: $row[type];");
  52.  print $bytes;  
  53.  }
  54. ?>
  55. <html>
  56. <head>
  57. <title>Upload an image to a database</title>
  58. </head>
  59. <body>
  60.   <font color="#FF3333"><?php echo $err ?></font>
  61.   <table>
  62.     <form name="myform" enctype="multipart/form-data" method="post">
  63.       <tr>
  64.         <td>Upload <input type="file" name="imagefile">
  65.           <input type="submit" name="xsubmit" value="Upload">
  66.         </td>
  67.       </tr>
  68.       <tr>
  69.        <td>Latest Image</td>
  70.       </tr>
  71.       <tr>
  72.         <td><img src="?pic=1"></td>
  73.       </tr>
  74.     </form>
  75.  </table>
  76. </body>
  77. </html>
  78.  
  79.  
Advertisement
Add Comment
Please, Sign In to add comment