dtio35880438 2015-12-30 00:21
浏览 16
已采纳

如何在一组PHP MySQL Select Queries之后插入水平规则?

I am currently working on developing a PHP website, and I would like to add a section to the home page that displays news headlines. The information to populate this section, like all other content on the site, will be pulled from a MySQL database. I have added the code that will let me do this and a little CSS before each part to format the display on the page and that works wonderfully. But, what I cannot work out is how to display all the content I want and insert a horizontal rule after each MySQL row is read. Right now, if I insert more than one row into the database table, it only displays the information from the new row and replaces the info from the previous. Refer to the image below to see how the page currently appears.

Screenshot of current page layout

Below is the code that I am using.

<div id="news">
<?php
$query = "SELECT news_date FROM news";
$result = mysqli_query($dbconnect, $query);
while($row=mysqli_fetch_assoc($result)) {
    $date = $row['news_date'];
}
?>
<?php
$query = "SELECT news_headline FROM news";
$result = mysqli_query($dbconnect, $query);
while($row=mysqli_fetch_assoc($result)) {
    $headline = $row['news_headline'];
}
?>
<?php
$query = "SELECT news_body FROM news";
$result = mysqli_query($dbconnect, $query);
while($row=mysqli_fetch_assoc($result)) {
    $body = $row['news_body'];
}
?>
<div class="date"><?php echo $date . "<br />" ?>
<div class="headline"><?php echo $headline . "<br />" ?>
<div class="headlinebody"><?php echo $body . "<hr />" ?>
</div>

As I've said, this will display the info the way I want it, but as soon as I add another "headline", the new replaces the old. I would like for all headlines to appear with a horizontal rule between the headlines (rows) and not each part. Any help you can provide would be appreciated. Thank you much in advance.

  • 写回答

1条回答 默认 最新

  • doufangmu9087 2015-12-30 00:28
    关注

    You can do this in 1 query and 1 loop.

    <div id="news">
    <?php
    $query = "SELECT news_date, news_headline, news_body FROM news";
    $result = mysqli_query($dbconnect, $query);
    while($row=mysqli_fetch_assoc($result)) { ?>
        <div class="date"><?php echo $row['news_date']; ?></div><br />
        <div class="headline"><?php echo $row['news_headline']; ?></div><br />
        <div class="headlinebody"><?php echo $row['news_body']; ?></div><hr />
    <?php }
    ?>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?