PHP while循环从数据库中获取发布数据

时间:2014-09-18 18:49:40

标签: php mysql sql loops while-loop

我正在从头开始创建自己的博客,主页按照发布时间顺序加载最新帖子。我使用前端控制器调用帖子并将数据存储在MySQL数据库中。网站本身很棒,帖子都完全没有问题。问题是让主页工作。

我为主页创建了一些PHP函数。它们通常按ID按降序排列帖子(数据库行),因为它是一个自动增量字段,并调用它们的数据。然后通过从数据库最顶行获取数据,将最新帖子显示为顶部的“特色帖子”,这是最新帖子。

这很好 - 当我回应结果时,它会像我想要的那样显示最新的帖子。

在下面我想要两个并排的盒子,用于第一个之前的两个帖子。所以我做了这个函数来调用它们:

function fetch_rest_posts_1($conn) {

$stuff = $conn->query("SELECT * FROM table WHERE is_post = 1 ORDER BY id DESC LIMIT 1,2");

    while ($row = $stuff->fetch_array()) {
        $i=1;
        return '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
                <h2>'.$row['title'].'</h2>
                <p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row['author'].' | <a href="http://www.domainname.com/'.$row['uri'].'#disqus_thread"></a></p>
                <p>'.$row['meta_description'].'</p>
                </div>';
                $i++;

    } // style="white-space:nowrap;width:100%;overflow:hidden;text-overflow:ellipsis"

}

当我回显结果,显示我想要的所有内容时它实际上工作得很好,但它只显示一个div,而不是两个。当我接受SQL查询并直接将其输入phpMyAdmin时,它给了我两行。我做错了什么?

(我把自动增加$ i放在那里,以便我可以隔离每个盒子并稍后改变样式。)

3 个答案:

答案 0 :(得分:1)

您的问题是由循环中的return语句引起的。您应该在功能顶部添加$return = '',将return替换为$result .=,将return $result替换为您的功能。

此外,循环计数器$i在每次迭代中都会重置。将初始分配移出循环。

编辑.=有意附加到$result,而不是将其替换为从下一个数据集构建的其他值。

答案 1 :(得分:0)

那是因为return会停止执行该函数尝试这种方法:

function fetch_rest_posts_1($conn) {
    $stuff = $conn->query("SELECT * FROM table WHERE is_post = 1 ORDER BY id DESC LIMIT 1,2");
    $post = array();
    while ($row = $stuff->fetch_array()) {
        $post[] = $row;
    }
    return $post;
}

因此功能的目的是获取数据,以便稍后打印它:

$row = fetch_rest_posts_1($conn);
for($i = 0; count(row); $i++){
 echo '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
        <h2>'.$row[$i]['title'].'</h2>
        <p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row[$i]['author'].' | <a href="http://www.domainname.com/'.$row[$i]['uri'].'#disqus_thread"></a></p>
        <p>'.$row[$i]['meta_description'].'</p>
        </div>';
}

答案 2 :(得分:0)

在循环外发起$i并使用echo()代替return() return()打破了循环 或使用

$result .= '<div id="post_'.$i.'" style="width:308px;height:215px;padding:5px">
                <h2>'.$row['title'].'</h2>
                <p>'.date('d/m/Y',strtotime($row['published_date'])).' by '.$row['author'].' | <a href="http://www.domainname.com/'.$row['uri'].'#disqus_thread"></a></p>
                <p>'.$row['meta_description'].'</p>
                </div>';
循环后

return $result;

相关问题