Save images into MySql database

A

Anonymous

Guest
Hi,
I want to save images in mysql database, how can i do that. Kindly give me its example. What data type of image field in mysql, which type of images format we can save in mysql database.
Thanks!
 
Hi,

As far as i have seen, the general method is to store only the name of the image in the db. The image itself will go to a fixed path where you know the images will be stored. Then you only need a varchar(30) or so to store the name in the db...

Regards.
 
Hi,
i know hat mathod but i want to store it in DB any other suggesion??
Thanks
 
Could you please tell me how to upload the file name into the DB the same time the image is uploaded?

Thank you.
 
The file name of the image is in the $GLOBALS variable (the exact variable name depends on your php version), but when you upload an image, do the following to see what variable stores the filename:

Code:
<?php

echo "<pre>";
print_r($GLOBALS)
echo "</pre>";

?>

With this you are able to retrieve the filename and so you can store the file in a folder on your server, after which you can save the entire path in a database to show the image later on.

You could also store the binary data from the file itself directly into the database, but that is not the fastest solution...
 
You can use BLOB field type (and/or its variant types), to store the images.
Also store in DB the name, size and type of the uploaded image.
Example:
Code:
<?php

// ...
// After submittion

if(isset($_POST['FileSubmitted'])){

  $image_types = Array ('image/bmp',
                        'image/jpeg',
                        'image/pjpeg',
                        'image/gif',
                        'image/x-png');

  $userfile = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], 'r'), 
    filesize($_FILES['userfile']['tmp_name'])));

    $file_name = $_FILES['userfile']['name'];
    $file_size = $_FILES['userfile']['size'];
    $file_type = $_FILES['userfile']['type'];

  if(in_array(strtolower($file_type), $image_types)) {
    $query  = 'INSERT INTO image_table (image_type, image, image_size, image_name, image_date) ';
    $query .= 'VALUES (';
    $query .= "'{$file_type}', '{$userfile}', '{$file_size}', '{$file_name}', NOW())";
    mysql_query($query);
    
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit();
  }
}

// ...

?>
And to retrieve the image data.
Example:
Code:
<?php

// ...

$query = 'SELECT * FROM image_table WHERE image_id = ' . $_GET['id'];
$result = mysql_query($query);

if(mysql_num_rows($result) > 0) {

  $row = mysql_fetch_array($result);
  $image_type = $row['image_type'];
  $image = $row['image'];
  
  header('Content-type: ' . $image_type);
  print $image;
}

?>
Hope it helps!
 
Back
Top