Maliha Khan
Maliha Khan

Reputation: 3

How to display images from a database using PHP?

My program needs to upload images, so an image (varchar) location is saved in a MySQL database. It's working so far.

Now I want to display images and this does not work. Here is the code:

include ('connect.php');
if(isset($_POST['submit'])){
    $filetemp= $_FILES['image'] ['tmp_name'];
    $filename= $_FILES['image'] ['name'];
    $filepath= "images/".$filename;

    move_uploaded_file($filetemp,$filepath);
    $sql=mysqli_query($con,"insert into  images (image) value ('$filepath')");
    if($sql){
        echo "uploaded";
    }
    else{
        echo " not uploaded";
    }
}

$sql=mysqli_query($con,"select * from images");
while($row=mysqli_fetch_array($sql)){
    echo "<img src=' images/".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image 
}   

?>

Upvotes: 0

Views: 4528

Answers (3)

supajason
supajason

Reputation: 670

You are adding images/ into the database then when you call the row to display the image you're adding images/ adding making it look in images/images/filename

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34924

remove images from image path, you already store this in image column in images table

echo "<img src='/".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image 

Upvotes: 2

Ahmed Ginani
Ahmed Ginani

Reputation: 6650

Correction :

$sql=mysqli_query($con,"select * from images");
while($row=mysqli_fetch_array($sql)){
    echo "<img src='".$row['image']."'>"; // the problem is here, its just displaying img icon, not actual image 
}

Also you need to get the actual path via __FILE__ in case if needed.

Upvotes: 0

Related Questions