如何使用PHP循环MySQL数据

时间:2015-03-03 14:39:58

标签: php mysql

我错误地购买了godaddy linux,现在我不知道如何做我以前用经典ASP做的简单照片库!

我创建了一个包含字段“image_path”和“no_of_images”等的MySQL表...我想要做的是连接到数据库表,将image_path导入img标记并循环直到存储在“no_of_images”中的数值满足了。

我尝试使用此代码执行此操作,但它无效。

<?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();
?> 

2 个答案:

答案 0 :(得分:4)

您在mysql函数中使用mysqli结果。您应该使用$result->fetch_row()

答案 1 :(得分:0)

如前所述,您需要切换到MySQL功能。使用此代码:

<?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();