我的PHP脚本只从表中返回一行

时间:2016-01-24 20:42:37

标签: php mysql

我在尝试从db检索数据时遇到了问题!

这是我提供的解析代码&将从MySQL表中获取数据:

$select_posts = "select * from posts order by RAND() LIMIT 0,6";
$run_posts = mysqli_query($con,$select_posts);
while($row=mysqli_fetch_array($run_posts)){
    $post_id = $row['post_id'];
    $post_title = $row['post_title'];
    $post_date = $row['post_date'];
    $post_author = $row['post_author'];
    $post_image = $row['post_image'];
    $post_keywords = $row['post_keywords'];
    $post_content = $row['post_content'];
    $post_summary = $row['post_summary'];
}

如您所见,我添加了LIMIT 0,6,这意味着"从第一行开始&显示表格中的6项" ...

但我不知道为什么只会出现1个结果。

这是我显示表格结果的页面:

<div id="box">
                <div class="BJadidBold">
                <?php 
                if (mysqli_num_rows($run_posts) > 0){ 
                    echo "
                    <h1>$post_title</h1>
                    <p>$post_summary</p></br>
                    <a style='float:right;font-size:30px;margin-top:-30px;' href='blog_post_content.php?post_id=$post_id'>readmore</a>
                    ";
                }else{
                    echo "<h1>No posts yet!</h1>";
                }
                ?>
                </div>
            </div>

我想在我的页面上显示至少6个项目。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

将第一个块更改为不覆盖:

$select_posts = "select * from posts order by RAND() LIMIT 0,6";
$run_posts = mysqli_query($con,$select_posts);
$post=array();
while($row=mysqli_fetch_array($run_posts)){
    $post[$row['post_id']]['id'] = $row['post_id'];
    $post[$row['post_id']]['title'] = $row['post_title'];
    $post[$row['post_id']]['date'] = $row['post_date'];
    $post[$row['post_id']]['author'] = $row['post_author'];
    $post[$row['post_id']]['image'] = $row['post_image'];
    $post[$row['post_id']]['keywords'] = $row['post_keywords'];
    $post[$row['post_id']]['content'] = $row['post_content'];
    $post[$row['post_id']]['summary'] = $row['post_summary'];
}

然后循环结果显示:

foreach($post as $p){
 echo "
 <h1>$p['title']</h1>
 <p>$p['summary']</p></br>
 <a style='float:right;font-size:30px;margin-top:-30px;' href='blog_post_content.php?post_id=$p['id']'>readmore</a>";
}