简体   繁体   中英

php mysql : creating image gallery

i am trying to learn php & mysql. I have a table called image in the gallery database. I have stored 4 images in that table. I have this php script which should fetch images from the database. But on trying this on xampp server i am getting only one image from the database which is repeating 4 times. The code is :

<?php
session_START();
//$id = $_GET['id'];
$id = 1;
while ($id <= 4) {
    $link = mysql_connect("localhost", "root", "#")
    or die("Couldn't connect");
    mysql_select_db("gallery") or die("Couldn't connect");
    $sql = "SELECT img FROM image";
    $result = mysql_query("$sql");
    if ($result != 0) {
        $row = mysql_fetch_assoc($result);
        header("Content-type: image/jpeg");
        echo $row['img'];
        mysql_close($link);
    } else {
        echo("No data");
    }
    $id = $id + 1;
};
?>

I would be highly thankful to you if my problem gets resolved.

You should really rewrite your loop to do only one query and then loop through the results, but to get it to work that way you need actually pass the id of the image you are trying to retrieve. Currently you are just grabbing the first image in the table, then running another query which grabs the first image, etc. etc.

Try this:

$sql = "SELECT img FROM image WHERE id = $id";

Hope that helps!

You can get all the images with below code.

<?php
session_START();
//$id = $_GET['id'];

    $link = mysql_connect("localhost", "root", "#") or die("Couldn't connect");
    mysql_select_db("gallery") or die("Couldn't connect");

    $sql = "SELECT img FROM image";
    $result = mysql_query("$sql");
    if (mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_assoc($result)){
            header("Content-type: image/jpeg");
            echo $row['img'];
        }
        mysql_close($link);
    } else {
        echo("No data");
    }
?>

Regards,

on Database first of all I would suggest that you do not store images in database but store the file name or file link.

on Folder function Thumbs() {

 $thumbs_path_from_root = 'images/galleryName/';
 foreach(glob($thumbs_path_from_root.'*.jpg') as $image){
    $id = explode('.', basename($image));
    echo "<div class='ecard_holder'><img src='".$image."' class='ecard_thumb' id='".$id[0]."' /></div>";
 }
}

this will search a folder you have specified and list all the images in a page you have used this function on

put this function "Thumbs()" in your html and style it well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM