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:
connection.php
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.
<?php $con=mysql_connect("localhost","root","guest123") or die(mysql_error()); mysql_select_db("10am",$con); ?>
regis.php
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:
<?php session_start(); include_once('connection.php'); error_reporting(0); $img_id=$_POST['id']; $imgpath=addslashes($_FILES['file']['name']); if($_POST['reg']) { 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"; } if($_POST['display']) { $r=mysql_query("select * from image where id=$img_id"); $row=mysql_fetch_array($r); $img=$row["imagepath"]; 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> <tr> <td height="55">Enter your Image Id</td> <td> <input type="text" name="id"/></td> </tr> <tr> <td height="55">Upload Your Pics</td> <td> <input type="file" name="file"/></td> </tr> <tr> <td align="center" colspan="2"><input type="submit" name="reg" value="Register"/> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" name="display" value="display"/> </td> </tr> </table>
Execution output: