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

使用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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler