How to fetch image from database in php ?

In this big and best tutorials, you going to learn how to fetch image from MySQL database in php including other related steps of fetching of image.

Fetch-Data-from-Database-in-PHP
Fetch-Data-from-Database-in-PHP

Related steps are as follow as:

  • The first step is to fetch image and display in table
  • The second step is to fetch image and display in div
  • The third step is to fetch multiple image and display in table
  • Forth step is to fetch uploaded image
  • Fifth step id how to fetch image and display

Above step you learn in more information.

Lets start with the step of talked about regarding : How to fetch image from MySQL database in php

Before start with the talked about regarding fetching of image.

First step to create table name called image in the MySQL database.

Below is the SQL query execute or run in phpmyadmin so table is created.

--
-- Table structure for table `image`
--
CREATE TABLE `image` (
  `id` int(11) NOT NULL,
  `title` varchar(500) NOT NULL,
  `imagename` text NOT NULL,
  `type` varchar(500) NOT NULL,
  `time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

After executing the above Sql query table is created as shown below.

Also Read: how to fetch images from database in php?

Now create the configuration file to configure MySQL database connection file name database_connect.php

database_connect.php

<?php 
   /* MySQL database configuaration */
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'phptutorial');
   $con  = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

   // Check connection
	if (mysqli_connect_errno()) {
	  echo "Failed to connect to MySQL: " . mysqli_connect_errno();
	  exit();
	}
?>

After the creation of a configuration file for MySQL database connection

Created Table Image
Created Table Image

The next step is to insert the image into the MySQL database.

To achieve the inserting of image into MySQL database I have to upload image.

To upload image, create form consisting with input field.

Below is the php script from which you come to know how the image file is uploaded.

Read Also:  AngularJS Search Filter Example with Demo

<?php 
	include("database_connect.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>How to fetch image from MySQL database in php</title>
</head>
<body>
<div style="background-color:rgba(100,200,255,0.5);" align="center">
    <form action="uploading.php" method="post" enctype="multipart/form-data">
        <h2>Image Uploading Section | <a href="users_list.php" >Veiw All Image</a></h2><br><br>
        <table>                             
        <tr><td height="70" width="100">Title</td><td><input type="text" autocomplete="off" required="required" name="ntitle" class="resizedTextbox"><br><br></td></tr>
        <tr><td height="70" width="100">Type</td><td><select name="ntype" id="ntype"><option vlalue="Banner">Banner</option><option vlalue="Logo">Logo</option></select><br><br></td></tr>
        <tr><td colspan="2"><input type="file" class="cck" name="profile_img" id="fileName" accept="image/*"><br><br></td></tr>
        <tr><td colspan="2"><input class="cck" type="submit" name="notification" value="Upload"/></td></tr>
        </table>
</form>
</div>
</body>
</html>

Output of above source code is as follow as:

Image Upload
Image Upload

As you can see the declaration of form with action calling file uploading.php.

In that file there php script for uploading of image into the MySQL database.

Also Read: Ajax Image Upload without Refreshing Page using Jquery

Below is the script of uploading image file which is called on click of upload button in the form.

<?php 
// Include config file
 include("database_connect.php");
if(isset($_POST['notification'])){
	$title = $_POST['ntitle'];
	$type = $_POST['ntype'];
	$uploadtime = date("Y-m-d H:i:s");
	$cname = $_FILES['profile_img']['name'];
}
if(!empty($cname))	{	
				$tname = $_FILES['profile_img']['tmp_name'];
				$tname = $_FILES['profile_img']['tmp_name'];
				$size	= $_FILES['profile_img']['size'];
				$name = $_SESSION['firstname'].date("his");
				$fext = pathinfo($cname, PATHINFO_EXTENSION);
				$fire = pathinfo($name,PATHINFO_FILENAME);
				$savename = $fire.".".$fext;
				$finalfile = "image/$savename";
														}
		if(!empty($cname)){
	 if($size < 500000){
				$check = move_uploaded_file($tname,$finalfile);
				if($check){
                                  $qry1 = "INSERT INTO `image`(`title`, `imagename`, `type`,`time`) VALUES            ('$title','$savename','$type','$uploadtime')";
                               $test =	mysqli_query($con,$qry1);
                               if($test = TRUE){?>
				<script>
				if(confirm("File Uploaded Sucessfully!!!"))
				{	document.location = 'users_list.php';
				}
				else
				{
					document.location = 'users_list.php';
				}
				</script>
				<?php
											}
					else {?>
					<script>
					if(confirm("file is not uploaded"))
			
				{	document.location = 'users_list.php';
				}
				else
				{
					document.location = 'users_list.php';
				}
				</script>
				<?php
						
				}
			}
	 }
	 else{
		 echo "file size is too large";	
	 }
 }else
 {	
	echo "Please select an file to upload";
 }												
 ?>

After clicking on upload button, image get inserted into MySQL database and image file is uploaded in folder path of image as it is give in above php script.

To understand more thoroughly below is folder structure.

Folder Structure Image
Folder Structure Image

After uploading two images, the two image get inserted into MySQL database.

Image Inserted into database
Image Inserted into database

And Image file is uploaded in image folder.
Image Uploaded and Inserted in database
Image Uploaded and Inserted in database

Now fetching the image from MySQL database.

To fetch the image from the MySQL database table I have to execute select SQL query depending upon the number of image requirement.

As in the above code you can see that after inserting of images into MySQL database successfully it redirect to display image file for display of image.

Read Also:  jquery remove item from array - How to remove specific value from array using jQuery?

The file for display of images is called as the file name users_list.php

users_list.php

<?php 
    // Include database_connect file
     include("database_connect.php");
    
     $baseurl = "http://".$_SERVER['SERVER_NAME']."/";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>How to fetch image from MySQL database in php</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"></script>
</head>
<body>
    
<table class="table table-bordered" border="2">
<tr> <td colspan="5"><center><h3>Previously Uploaded | <a href="index.php" >Add Image</a></td></tr>
  <tr> 
      <tr><center><th>Title</th><th>Image</th><th>Type</th><th>Action</th></center></tr>
    <?php $fetchqry = "SELECT * FROM `image` ORDER BY time DESC"; 
    $result=mysqli_query($con,$fetchqry);
    $num=mysqli_num_rows($result);
    if($num > 0){
    while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ ?>
      <tr><td><p><?php echo $row['id']; ?><?php echo $row['title'];?></p></td><td><img width="auto" src="image/<?php echo $row['imagename']?>" width="450" height="200" /> </td>
      <td><?php echo $row['type']; ?></td><td width="10%"><input type="button" class="btn" value="Delete" id="button" onclick="deleteme(<?php echo $row['id']; ?>)"></td></tr>  
      <?php
    }
    }
    ?>
  </tr>
</table>
</div>
<script language="javascript">
                function deleteme(delid) 
                {
                        window.location.href='deleteimage.php?id='+delid+'';
                        return true;
                }
                </script>
</body>
</html>

After uploading of images the output is given as below.

Fetched Image from Database table.
Fetched Image from Database table.

Finally done with the display of image from the MySQL database.

Now I am going to talked about other related step.

How to fetch image from MySQL database in php and display in table

Above is the full example of displaying of image in table. You can check with users_list.php file in which all image is get fetch using select query as well as display the result in table.

How to fetch image from MySQL database in php and display in div

To Display the Image from MySQL database in div tag just replace with table tag in users_list.php file in the above source code.

After doing this data get display in the div tag of HTML.

How to fetch multiple image from MySQL database in php and display in table

Fetching of Multiple images depends upon select SQL query which is used in the above complete code in users_list.php file. Just execute below SQL query and fetched all images run in a while loop.

Read Also:  MySQL SELECT DISTINCT, COUNT, ROWS EXAMPLE

SELECT * FROM `image` ORDER BY time DESC

Also Read: insert delete image from folder in php with jQuery

How to fetch uploaded image from MySQL database in php

To fetch upload image from MySQL database is similar as I talked about above mysql Query, so check with the all point above.

How to fetch image from MySQL database in php and display

To get image HTML form the MySQL database and display the image from the MySQL database which I have talked about in above example.

First I have to insert the image into the MySQL database with the HTML form submit which shown in above full source code.

To get image from the MySQL database is given in users_list file in above.

So go through all file and execute the code and image get display.

Conclusion:

Finally, I done with all talked about regarding how to fetch image from MySQL database in php.

I hope you liked my this Tutorials. If you have any queries or any question regarding this, Feel free to comment on Me.