954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

adding images to a database

hello,
I am currently working on CMS and I want a way for the user to upload images to go along with their post

how would I upload the image with php and then add it into the database for later retrieval when people look at the posts?

tape enterprise
Junior Poster in Training
59 posts since Feb 2010
Reputation Points: 10
Solved Threads: 1
 

you can use some editors like : http://www.openwebware.com/

Shanti C
Posting Virtuoso
1,642 posts since Jul 2008
Reputation Points: 137
Solved Threads: 162
 


I think you can save the image on the server drives but not on the database itself. The path of the image is the one that saves in the database.

lyrico
Junior Poster in Training
94 posts since Dec 2010
Reputation Points: 33
Solved Threads: 15
 
I think you can save the image on the server drives but not on the database itself. The path of the image is the one that saves in the database.

That's one way to do it, but you can also save the actual image in the database in a BLOB (Binary Large OBject) column. You could do something like this:

Create a table in the database to store the images:

CREATE TABLE images (
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  mime VARCHAR(50),
  filename VARCHAR(255),
  imagedata MEDIUMBLOB
);


To add the image to the database:

$yourimage = (object)$_FILES[$your_image_input_name];
if ($yourimage->error == UPLOAD_ERR_OK)
{
  $dbinsert = new stdClass;
  $dbinsert->mime = $yourimage->type;
  $dbinsert->filename = $yourimage->name;

  // read the image file into your data object
  $dbinsert->imagedata = 
    addslashes(fread(fopen($yourimage->tmp_name, 'r'), $yourimage->size));

  // execute a sql statement inserting the values in $yourimage into the database
}
else
{
  // there was an error with the form submission
}


To later view your image, link to viewimage.php?id=THE_ID_OF_THE_IMAGE_YOU_WANT:

// file viewimage.php
$id = $_GET['id'];

// validate the id by trying to load the image from the database
// e.g. $image = your_database_query_function("SELECT * FROM images WHERE id='{$id}'");

// now that you have the image data, send it to the browser (there
// are surely better ways to do this, but this is what comes to
// mind and I've used it in the past)
header("Content-type: {$image->mime}");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=\"{$image->filename}\"");
print(stripslashes($image->imagedata));
exit;
dcdruck
Light Poster
33 posts since Jul 2009
Reputation Points: 16
Solved Threads: 4
 

thanks that was helpful!

tape enterprise
Junior Poster in Training
59 posts since Feb 2010
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: