Popular Articles | Latest Articles | Categories | RSS Feeds

Login  |  Register

How to upload images to mySQL within PHP

Published on 2/6/2007 by Dotnetindex
 Vote this tutorial:

More articles in PHP

Aim of this article is to sho you the simples way to uplaod images to mySQL database. First you need to create a custom database table. The name of this table can be named as "images_table". Now here is the SQL code for creating the table.

images_table.sql

CREATE TABLE `images_table` (
`imageID` int(11) NOT NULL auto_increment,
`imageName` varchar(25) NOT NULL default '',
`imageFile` longtext NOT NULL,
PRIMARY KEY (`imageID`)
)  AUTO_INCREMENT=1 ;

This is our upload HTML file. There will be no server-side coding on this file :

imageupload.php



Upload Image



Name :

Image :






Now this is the rest of the code. This php file will insert the image to our database.

imageupload.php



  /*
    This function take the image from form variables
                            */

function getImageFile($file){
$takeFile = fopen($file, "r");
$file = fread($takeFile, filesize($file));
fclose($takeFile);

return $file;
}

  /*
    We learn image type using this function
    Because we will let onlt gif, jpg and png images can be uploaded
                            */

function getfileType( $name ){
$name = explode(".", $name);
$name = array_reverse($name);
$name = $name[0];
return $name;
}

$allowedImageTypes = array("gif","jpg","png");
if(empty($_FILES['image_file']['tmp_name'])){
echo "File not uploaded";
}
else {
$fileType = $_FILES['image_file']['name'];

if(in_array(getfileType($fileType), $allowedImageTypes)){
$fileContent = getImageFile($_FILES['imgFile']['tmp_name']);

$uploadedImage = chunk_split(base64_encode($fileContent));

$query = "INSERT INTO images_table VALUES('NULL','$imgName','$uploadedImage')";

$result = mysql_query($query);

if(mysql_affected_rows() > 0){

echo "Image has been inserted succesfully";
}
else {
echo "Image can not be inserted check your submission";
}
}
else {
echo "This is not a true image type";
}
}

Happy Coding

Comments:
no comments submitted


Only members can write comments.Please, login / register to write comment.

Latest Posts

Active News Manager - news management system



ASP.NET Resources, Reviews

ASP Resources, Reviews

PHP, ASP, .NET, JSP Resources, Reviews




Who's online

  • There 90 online users.

ASP.NET Resources, Reviews

ASP Resources, Reviews

PHP, ASP, .NET, JSP Resources, Reviews

Hotscripts.com Free Photoshop, Flash and 3DS MAX tutorials