gpt4 book ai didi

php - 使用 foreach 循环遍历 MySQL 中的所有行

转载 作者:行者123 更新时间:2023-11-29 07:42:41 24 4
gpt4 key购买 nike

我正在创建一个函数,该函数循环遍历 MySQL 数据库的所有行,然后使用与当前 id 相关的特定数据填充一堆 anchor 标记。我的问题是,它只会用信息填充第一个标签,而根据它应该在哪一行,后面不会填充其他标签。希望代码能更好地解释这一点。

    public function getLinks() {
$output = "";

$data = $this->_db->get('SELECT *', 'shutins', array('id', '>', 0));

echo $data->count(); // Currently returns 2

for($i = 1; $i < ($data->count() + 1); $i++) { // Set the count to 3 to make sure it should continue
$this->find($i); // Gets the first row only
$output .= "<a href=\"shutin.php?id={$this->data()->id}\" class=\"link\"><span>{$this->getName()}</span> <img class=\"next\" src=\"img/next.png\" width=\"20\"/></a>";
$i++; // Doesn't seem to increment then start again
}

return $output;
}

如果您需要查看更多我的代码文件,我很乐意提供它们。

最佳答案

您正在双倍递增您的 $i多变的。 for 循环的第三个“参数”是每次迭代之后执行的语句。你的第一个循环将有 $i为 1,那么当它开始第二次迭代时 $i将是三个。它将检查您的条件( $i < ($data->count() + 1) ),该条件将为 false 并且循环将结束。

旁注;循环的第二个“参数”用于在每次迭代开始时运行(并检查)的语句。编写循环的更有效方法是:

for($i = 1, $count = $data->count() + 1; $i < $count; $i++) { 

这是因为执行计数和加法来填充 $count变量仅发生一次,而不是在循环中的每次迭代中发生。

关于php - 使用 foreach 循环遍历 MySQL 中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28598420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com