dtncv04228 2015-02-19 04:03
浏览 212
已采纳

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

Im creating a function that cycles through all the rows of a MySQL database, then populates a bunch of anchor tags with specific data pertaining to the then current id Its on. My problem is that it will only populate the first tag with the information, and no others after it according to what row it should be on. The code will hopefully better explain this.

    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;
    }

If you need to see more of my code files, Im happy to provide them.

  • 写回答

2条回答 默认 最新

  • dongshungou7699 2015-02-19 04:07
    关注

    You are double incrementing your $i variable. The third "parameter" of a for loop is statements to execute after each iteration. Your first loop will have $i as 1, then when it starts the second iteration $i will be three. It will check your condition ($i < ($data->count() + 1)) which will be false and the loop will end.

    Side note; the second "parameter" of the loop is for statements to be run (and checked) at the beginning of each iteration. A more efficient way of writing the loop will be:

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

    This is because the count and addition performed to populate the $count variable only happens once, not for every iteration in the loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错