FREE E LEARNING PLATFORM
INTRODUCTION SCHEMAS DATA MODELS E-R MODEL
 

Upload Image into Database






Before we proceed , I would like to inform you that we cannot insert an image in a database.

So, how do we do that ? In such casses we insert the name of the image in the databse , upload the image in another folder and while displaying it we extract the name from the databse to display the image.


First Step

First we create the form page to upload the image . In my case I have created a form with name and upload image section.You can download the codes from below , from download section.


form.png

Step 2

After we design the form page , then we create a database and a table in the database .I created a databse image and in the database I created a table as image.

CREATE TABLE IF NOT EXISTS `image` (
  `id` int(6) UNSIGNED NOT NULL AUTO_INCREMENT,
  `firstname` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

Step 3

Once we have created a database , we need to go back to the form page. From the form page , you can see a submit button . On Submit , we take the value of firtname and image in a varibale.

$f_name = $_POST["f_name"];
$image = $_FILES['image']['name'];

Get the extension of the image

$target = "images/".basename($image);
		$tar = basename($image);
		 $ext = pathinfo($target, PATHINFO_EXTENSION);

Insert into Databse

The following set of codes will insert the data in the dabase .
	$sql = "INSERT INTO image (firstname, image)
VALUES ('$f_name', '$tar')";

Copying the uploaded file

 move_uploaded_file($_FILES['image']['tmp_name'], $target);}

move_uploaded_file($_FILES['image']['tmp_name'], $target);} This command will copy / move the uploaded file to the folder mentioned in target. We have used the name of the folder as image, where all uploaded images will be saved.

Display

As we proceed further , we have displayed the last inserted image. $last_id = mysqli_insert_id($consub); . The querry will display the id of last inserted data. Once we get the id of last inserted data, we extract the full details including the name of the image from database and display the image .

Get the last inserted data.

<?php 
$last_id = mysqli_insert_id($consub);
$sq = "SELECT * FROM image WHERE id = '" .$last_id ."'";
$profile=mysqli_query($consub,$sq);
while($row=mysqli_fetch_assoc($profile))
{ $fname = $row['firstname'];
$image = $row['image'];
}
?>
<img src="images/<?php echo $image;?>" />

Download Source Code

Full Source Code in PHP MySql
Download »

You may also Find this interesting

Relational Calculus

Keys

DBMS Normalization

Second NF


Leave Comment