0

我有以下 PHP 代码:

$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_error());
while ($row = mysql_fetch_assoc($getnews)) {
  $id = $row['id'];
  $title = $row['title'];
  $body = $row['body'];
  $date = $row['date'];
  echo "<div class=\"title\">$title</div><br>";
  echo nl2br($body);
  echo "<br><div class=\"date_time\">".time_ago($date)."</div>";
  echo "<hr>";
}

这用于创建新闻提要,我使用 echo 打印出更新中的内容。有没有一种方法可以让我使用列表来打印每个更新,而不是我目前正在做的方式?

或者是否可以围绕 while 循环创建的每个更新创建一个 div?

如果问题不清楚,我很抱歉,但感谢所有帮助!

我的新闻提要在 twitter 等新闻提要中创建更新。每个更新都使用 echo 打印出来并被包围


. 我试图找到一种可以为每个更新的整个布局创建列表或 div 的方法。我发现很难安排每次更新中发生的事情。

4

1 回答 1

1

以下代码应该可以帮助您。只需按照您希望的方式回显 html。

$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_error());
while ($row = mysql_fetch_assoc($getnews)) {
    $id = $row['id'];
    $title = $row['title'];
    $body = $row['body'];
    $date = $row['date'];
    echo "<div class='news-article'>";
    echo "<div class=\"title\">$title</div><br>";
    echo nl2br($body);
    echo "<br><div class=\"date_time\">".time_ago($date)."</div>";
    echo "</div>";
    echo "<hr>";
}

很多时候,很多这样的回声语句只会混淆你正在尝试做的事情。

$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_error());
while ($row = mysql_fetch_assoc($getnews)) {
    $id = $row['id'];
    $title = $row['title'];
    $body = $row['body'];
    $date = $row['date'];
    ?>
    <div class='news-article'>
    <div class="title"><?php echo $title ?></div><br>
    <?php echo nl2br($body); ?>
    <br><div class="date_time"><?php echo(time_ago($date)) ?></div>
    </div>
    <hr>
    <?php
}

如果你想完成与无序列表相同的事情,你会这样做。

$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_error());
echo "<ul class='article-list'>";
while ($row = mysql_fetch_assoc($getnews)) {
    $id = $row['id'];
    $title = $row['title'];
    $body = $row['body'];
    $date = $row['date'];
    ?>
    <li class='news-article'>
    <div class="title">$title</div><br>
    <?php echo nl2br($body); ?>
    <br><div class="date_time"><?php echo(time_ago($date)) ?></div>
    </li>

    <?php
}
echo "</ul>";
于 2013-05-13T02:55:44.840 回答