PHP MySQL虽然循环只返回最后一行

时间:2018-05-01 13:12:32

标签: php mysql

当我点击摄影师时,我的任务是提供与摄影师相关的所有照片列表。我需要回应照片列表,但目前只有最后一行正在回应。

返回的行应如下所示(减去项目符号点):

1 Amager Standpark Sunset 2010-07-01 _img/1/1.jpg 1
1 Field Landscape 2010-07-09 _img/1/2.jpg 1

但是我的代码只返回这个:

1 Field Landscape 2010-07-09 _img/1/2.jpg 1

以下是我的代码:

            // SQL query to get all photo data from specific photographer
$query = mysqli_query($con, "SELECT * FROM Photograph WHERE PhotographerId='$photographerID'");
$photos = mysqli_fetch_assoc($query);
$num = mysqli_num_rows($query);

if ($num == 0) {
    echo 'This are no photographs present for this photographer.';
} else if ($num > 0) {

    $list = '';

    while ($photos = mysqli_fetch_array($query)) {

        $list .= $photos['PhotographerId'] . ' ' . $photos['PhotographName'] . ' ' .
                $photos['Date'] . ' ' . $photos['PhotographURL'] . ' ' .
                $photos['Visible'] . ' </br>';
    }

    echo $list;

}

1 个答案:

答案 0 :(得分:3)

在使用第一组结果有效运行查询后,您正在调用mysqli_fetch_assoc()。然后,一旦开始循环,就开始t =第二行。

删除它将解决您的问题并使第一个结果集可用于您的循环。

您也可以在循环中使用mysqli_fetch_assoc()代替mysqli_fetch_array()mysqli_fetch_array()会返回您不需要的查询的关联和数字索引结果。

// SQL query to get all photo data from specific photographer
$query = mysqli_query($con, "SELECT * FROM Photograph WHERE PhotographerId='$photographerID'");
$num = mysqli_num_rows($query);

if ($num == 0) {
    echo 'This are no photographs present for this photographer.';
} else if ($num > 0) {

    $list = '';

    while ($photos = mysqli_fetch_assoc($query)) {

        $list .= $photos['PhotographerId'] . ' ' . $photos['PhotographName'] . ' ' .
                $photos['Date'] . ' ' . $photos['PhotographURL'] . ' ' .
                $photos['Visible'] . ' </br>';
    }

    echo $list;

}

我不知道你从哪里获得$photographerID,但如果是用户输入,则此代码容易受到SQL Injection Attacks的攻击。您应该考虑使用prepared parameterized statements来避免此风险。