14 - MySql and PHP connectivity

Mini Project code: Inserting Image in MySql database and retrieving it using PHP code


In this sample code, we are using PHP code to create a form. User can choose any image from his system and submit it. This image will be saved in MySql database.

In the same form we will create a Display button, user can enter any Image Id and this image will be retrieved from Database and displayed on form.

For this project code, first of all we have to create a database table in MySql to store image.

Create MySql database table Image:

Open MySql prompt and provide following query to create table:

     Create table image
     id int(10),
     Imagepath varchar(30)

After creating database table, we will use following code to upload and Retrieve image from database:


This PHP code is used to establish connection of PHP and MySql:

Here we are using root as username

And guest123 as password to connect with MySql server.

  $con=mysql_connect("localhost","root","guest123") or die(mysql_error());


This PHP code is main code where we will use a form as an Interface, User will choose image from system and submit it in database:

   mysql_query("INSERT INTO IMAGE values('$img_id','$imgpath')");
   move_uploaded_file($_FILES["file"]["tmp_name"], "userImages/" .$_FILES["file"]["name"]);
   echo "$imgpath";    
   echo "<br/>";
   echo "$img_id";
  $r=mysql_query("select * from image where id=$img_id");
  echo "<img alt='image not upload' src='userImages/$img' height='220' width='220'/>";


<form method="post" enctype="multipart/form-data">
<table width="438" border="5" align="center">
  <font color="#FF0000"><?php echo $err; ?></font>
    <td height="55">Enter your Image Id</td>
    <td>    <input type="text" name="id"/></td>
    <td height="55">Upload Your Pics</td>
    <td>    <input type="file" name="file"/></td>
    <td align="center" colspan="2"><input type="submit" name="reg" value="Register"/>
    <td align="center" colspan="2">
     <input type="submit" name="display" value="display"/>

Execution output:

Fig - Execution Output - 1


Fig - Execution Output - 2


Fig - Execution Output - 3


Fig - Execution Output - 4



Like us on Facebook