Storing Images In MySQL
Note: This article has been replaced by Storing Images in MySQL Revisited
(by Quentin Zervaas, 2010).
We've left this article here for historical purposes, but we strongly recommend you use
the newer article instead.
The Upload Function
Here we need to do several things to successfully upload the image. We need to create a function that does several things. An outline might look like this:
- Check the file is of an allowed type
- Check if the uploaded file is no bigger thant the maximum allowed size
- Format the binary data for insertion
- Connect to the database
- Insert the data
We have already checked that an image has been uploaded with the first if statement. We should also check that it is an uploaded file, so now we need to check if the file is of an allowed type with getimagesize(). We will begin our function with that and build on it from there.
Listing 5 listing-5.php
// the upload function function upload(){ if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check the file is less than the maximum file size if($_FILES['userfile']['size'] < $maxsize) { // prepare the image for insertion $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // $imgData = addslashes($_FILES['userfile']); // get the image info.. $size = getimagesize($_FILES['userfile']['tmp_name']); // put the image in the db... // database connection mysql_connect("localhost", "$username", "$password") OR DIE (mysql_error()); // select the db mysql_select_db ("$dbname") OR DIE ("Unable to select db".mysql_error()); // our sql query $sql = "INSERT INTO testblob ( image_id , image_type ,image, image_size, image_name) VALUES ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name']}')"; // insert the image if(!mysql_query($sql)) { echo 'Unable to upload file'; } } } else { // if the file is not less than the maximum allowed, print an error echo '<div>File exceeds the Maximum File limit</div> <div>Maximum File limit is '.$maxsize.'</div> <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].' bytes</div> <hr />'; } }



