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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?