首页 > 解决方案 > 使用相同的 SELECT 重复 WHILE

问题描述

为什么我不能使用相同的while两次?

我想在页面上重复相同的内容,但我不能,只需加载第一个。

例子:

$rs = $mysqli->query("SELECT * FROM site WHERE id = '".$cliente."' ");
$row = $rs->fetch_assoc();

While 1(位于网站顶部)

<?php do{ ?>
    <option value="<?php echo $ID; ?>">
        <?php echo $nome; ?>
    </option>
<?php } while ($row = $rs->fetch_assoc()); ?>

While 2(位于站点末尾)

<?php do{ ?>
    <option value="<?php echo $ID; ?>">
        <?php echo $nome; ?>
    </option>
<?php } while ($row = $rs->fetch_assoc()); ?>

谢谢你。

标签: phpmysqlmysqli

解决方案


Store your results in an array instead, and loop that where needed. Otherwise you will need to reset the cursor of your result before looping again.

$query = $mysqli->query("SELECT * FROM site WHERE id = '".$cliente."' ");
$result = $query->fetch_all(MYSQLI_ASSOC);

// Loop wherever needed
foreach ($result as $r) {
    // Use $r
}

// Loop the result again!
foreach ($result as $r) {
    // Use $r
}

Also recommend you use a prepared statement instead of using a direct query with variables injected into it.


推荐阅读