How do different websites server like facebook fetch our images from databse. How do i fetch all images from a database in PHP?

Image is not stored in database. Only the path of the image is stored in database.

For example -

On uploading image it will get stored on desired server/folder.

Now you can fetch your image by simply writing code -
<img src = "fetch_path_stored_in_database" />
So, src will give the path of folder which you have stored in database.



  1. Download xampp for the php file to run. https://www.apachefriends.org/download.html
  2. Download mysql for the database connection. https://www.mysql.com/downloads/
  3. Go to in directory where you have installed xampp and enter it and save your file in htdocs folder with Image.php name made in notepad whose code is below.
  4. Go to directory where you have installed mysql and run mysql.exe then make new database by typing the command-
    CREATE DATABASE dbname;
  5. Now write query to create table
    CREATE TABLE tablename (location char[50]);
  6. Now write query to store location. It will be good if you also keep you images in htdocs folder.
    INSERT INTO tablename(location) VALUES ('imgname.jpg');
  7. If you want store more than use the above insert query for the same.
  8. Make file named-Image.php in notepad.

I am writing code in php.

Image.php

<?php
//connection to sql database
$con = mysqli_connect('localhost','root');


//select database
mysqli_selectdb($con,'dbname');


//fetching location stored in table
$query = `SELECT location FROM tablename`;


//running query
$locations = mysqli_query($con, $query);

$row= mysqli_fetch_array($con, $locations)

while($row)
{
echo "<img src='".$row['location']."' /> <br/>";
}


//close connection
mysqli_close($con);
?>


  1. Finally, run the xampp.exe in xampp folder and go to the browser and type http://localhost/Image.php
  2. You will fetch your images from databse :)

Feel free to ask any doubt.

Post a Comment

0 Comments