How to insert an image to a MySQL table in PHP

Hi, guys 🙂 Don’t think this is another post of inserting some data to a MySQL database. Because you cannot upload an image and store it in a database as you do in normal values. You have to use basename method and copy method in this process where you have to handle Exception also.

Lets first see the our form interface as usual 😉

Form
Figure 1

When you click on the Submit button it will direct you to insert.php page where relevant insert query has written. Actually there is a JavaScript validation part also. I have omitted that part from this post and I will explain in another post.

The content of insert.php file as follows;

...
require("functions.php");

$var_imageName = $_POST[@textfieldImageName];

$var_image = basename($_FILES[@fileFieldImage]['name']);
$var_path = "my_images/".$var_image;

checkImg("a");	

$stringQuery = "INSERT INTO `test_image` (`image_name`,`image`) VALUE ('$var_imageName', '$var_path')";
$insert_query = mysql_query($stringQuery) or die ("Query failed". mysql_errno());

function checkImg($var_image){
  if($var_image == NULL){		  
	throw new Exception("You have not add an image");
	}
  return true;
}

try{		
  checkImg($var_image);
  $var_copy = copy($_FILES[@fileFieldImage]['tmp_name'], "$var_path" );
  **** 'Image added successfully. Redirecting You Back....';
}
catch(Exception $e){
  **** 'Message: ' .$e->getMessage();
  **** 'Redirecting You Back...';  
}
...

Place **** with echo word. I think now you are familiar with the redirect statement. If you forgot that here it again

echo ‘<meta http-equiv=”refresh” content=”2;url=index.php”>’;

That is the end of this post. Thank you 🙂

Advertisement

About AnujAroshA

Working as a Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in MySQL, PHP examples. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s