Mihail Andreev
Mihail Andreev

Reputation: 3

How to upload and display images in mysql

I would like to ask you how can I properly stored an image both in mysql and in a folder at the moment with this code:

<?php

if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

          // Temporary file name stored on the server
          $tmpName  = $_FILES['image']['tmp_name'];  

          // Read the file 
          $fp     = fopen($tmpName, 'r');
          $data = fread($fp, filesize($tmpName));
          $data = addslashes($data);
          fclose($fp);


          // Create the query and insert
          // into our database.
          $query = "INSERT INTO tbl_images ";
          $query .= "(images) VALUES ('$data')";
          $results = mysql_query($query, $conn);

          // Print results
          print "Thank you, your file has been uploaded.";

}
else {
   print "No image selected/uploaded";
}


if (!mysql_query($sql, $link))
   {
   die('Error: ' . mysql_error());
   }

?>'

Also how properly to display it. My database for the images is id, images. Do I need anything more for the job or that is enough. Thank you.

Upvotes: 0

Views: 711

Answers (2)

Prem
Prem

Reputation: 707

From the above code, image will be saved in database not in folder. To save in folder you have to use a below code after insert query.

move_uploaded_file($tmpName,"upload/" .$filename );

here upload is folder name.

Upvotes: 1

DeDav
DeDav

Reputation: 353

If you want to store image in database you can use base64_encode method

$image = file_get_contents('filename.gif');
$imencoded = base64_encode($image);   
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$imencoded')";

But storing image in db is not recommended and it will not support in IE6 & 7.

Upvotes: 0

Related Questions