循环并重用fetch_assoc()

时间:2016-01-14 18:45:34

标签: php while-loop

对于我正在构建Flash游戏网站的项目,我想知道如何重用这段代码:

        $result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");

                <?php
                echo "<div class='row list jumbotron'>";
                while($data = $result->fetch_assoc()) {

                    echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
                    echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
                    echo "</a></div>";
                }
                echo "</div>";
            ?>      

我需要能够再次使用$data['category']动态填充我的所有游戏类别的菜单。如果我只是尝试再次使用while循环,但只有一个可以工作。另一个保持空白。非常感谢!

1 个答案:

答案 0 :(得分:2)

您需要将结果指针调整为指向结果集的开头,以便您可以再次使用它。为此使用mysqli_result::data_seek()方法。

以下是参考资料:

所以你的代码应该是这样的:

<?php

    $result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");

    echo "<div class='row list jumbotron'>";
    while($data = $result->fetch_assoc()) {

        echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
        echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
        echo "</a></div>";
    }
    echo "</div>";

    // adjust the result pointer to point to the beginning of the result set
    $result->data_seek(0);

    // now you can use the result set again
    // for example, you can iterate through it using while loop again

?>