Johnny B
Johnny B

Reputation: 1

How to loop MySQL data with PHP

I have purchased godaddy linux by mistake and now I have no clue how to do my simple photo gallery which I used to do with classic ASP!

I have created a MySQL table with fields "image_path" and "no_of_images" etc... What I want to do is connect to the database table, get image_path into img tag and loop till the numeric value stored in "no_of_images" is met.

I have tried to do this with this code but it is not working.

<?php
    $servername = "localhost";
    $username="";
    $password="";
    $dbname="";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $myid = $_GET['id']; 
    $sql = "SELECT * FROM gallery where id='$myid'";
    $result = $conn->query($sql);

    $row = mysql_fetch_row($result);
    $image_path = $row[3]; 
    $no_of_images = $row[4]; 
    $x = 1;

    while($x <= $no_of_images ) {
        echo "<img src="$image_path"/"$x".jpg><br>";
        $x++;
    } 

    $conn->close();
?> 

Upvotes: 0

Views: 79

Answers (2)

ajtrichards
ajtrichards

Reputation: 30565

As a previous answer states - your switching to a MySQL function. Use this code:

<?php

$servername = "localhost";
$username   = "";
$password   = "";
$dbname     = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$myid   = $_GET['id']; 
$sql    = "SELECT * FROM gallery where id='$myid'";
$result = $conn->query($sql);

$x      = 1;

while ($row = $result -> fetch_row()){

     $image_path = $row[3]; 
     $no_of_images = $row[4]; 

     echo "<img src=" .$image_path. "/" .$x. ".jpg><br>";
     $x++;

}

$conn->close(); 

Upvotes: 0

nickforall
nickforall

Reputation: 614

You are using a mysqli result in a mysql function. You should use $result->fetch_row()

Upvotes: 4

Related Questions