PHP / SQL:为什么mysqli_fetch_assoc的循环不起作用?

时间:2017-05-19 06:37:23

标签: php mysql

我从sql db中获取一些数据,并希望循环遍历每一行。

这就是我写的:

<?php

$result = mysqli_query($con,"SELECT * FROM bewertungen;");

while($rating = mysqli_fetch_assoc($result) ){
    echo "number of rows: " . mysqli_num_rows($result) . "<br>";
    $sql="
        SELECT SUM(rating_direction)
        FROM commentratings
        WHERE comment_ID = '".$rating['ID']."';
    ";
    echo "ratingID: " . $rating['ID'] . "<br>";

    $result = mysqli_query($con,$sql);
    if (FALSE === $result) die("Select sum failed: ".mysqli_error);
    $row = mysqli_fetch_row($result);
    $sum = $row[0];
    if ($row[0] == false) $sum = 0;

    echo "sum: " . $sum ."<br>";

    $sql="
        UPDATE bewertungen
        SET Bewertung_Kommentar = '$sum'
        WHERE ID = ".$rating['ID'].";
    ";

    if ($con->query($sql) == TRUE) {
        echo 'success';
    }
}

?>

当我运行它时,它会返回

number of rows: 6
ratingID: 22
sum: -1
success

这一切都是正确的:行数,第一行的ratingID和总和。

但是为什么它不会循环通过所有其他行呢?我在另一个部分使用过它并且工作正常......

提前致谢, 儒略

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php

$result = mysqli_query($con,"SELECT * FROM bewertungen;");

while($rating = mysqli_fetch_assoc($result) ){
echo "number of rows: " . mysqli_num_rows($result) . "<br>";
$sql="
    SELECT SUM(rating_direction)
    FROM commentratings
    WHERE comment_ID = '".$rating['ID']."';
";
echo "ratingID: " . $rating['ID'] . "<br>";

$result2 = mysqli_query($con,$sql);   //result -> result2
if (FALSE === $result2) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($result2);    //result -> result2
$sum = $row[0];
if ($row[0] == false) $sum = 0;

echo "sum: " . $sum ."<br>";

$sql="
    UPDATE bewertungen
    SET Bewertung_Kommentar = '$sum'
    WHERE ID = ".$rating['ID'].";
";

if ($con->query($sql) == TRUE) {
    echo 'success';
}
}

?>