While语句的问题


issue with While statement

所以我正在尝试拉HEADLINES。。我保存在数据库中的,它们都有唯一的ID。。我需要一种能够调用它们的方法,例如键入或ID。

$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
while($rfr=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
   <div class="row">
    <div class="col-lg-4">
    <img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
      <h2><?php echo $rfr['headline'];?></h2>
      <p>V.A. conducts study to determine effectiveness</p>
      <p><a class="btn btn-primary" href="#" role="button">Read More &raquo;</a></p>
    </div>

    <div class="col-lg-4">
    <img src="imgs/news/n4.jpg">
      <h2><?php echo $rfr['headline'];?></h2>
      <p>The Rev. Daniel Berrigan, a Roman Catholic priest and peace activist who was imprisoned for burning draft files in a protest against the Vietnam War, died Saturday. He was 94.</p>
      <p><a class="btn btn-primary" href="#" role="button">Read More &raquo;</a></p>
   </div>
    <div class="col-lg-4">
    <img src="imgs/news/n1.jpg">
      <h2><?php echo $rfr['headline'];?></h2>
      <p>President Barack Obama is getting one more chance to poke fun at fellow politicians, the press and himself at the annual White House Correspondents' Dinner.</p>
      <p><a class="btn btn-primary" href="#" role="button">Read More &raquo;</a></p>
    </div>
 <?php
  }
  ?>

不过,每次我运行此代码时。。它每次只输入ID 1的标题。而且它做了很多重复的帖子。。

我想让它在那种类型的所有标题中进行选择。。这就是为什么我使用WHILE()

请尝试以下操作:

$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $rfr) {
?>
<div class="row">
    <div class="col-lg-4">
        <img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
        <h2><?php echo $rfr['headline'];?></h2>
        <p>V.A. conducts study to determine effectiveness</p>
        <p><a class="btn btn-primary" href="#" role="button">Read More &raquo;</a></p>
    </div>
    ...
</div>
<?php } ?>

为什么不使用foreach?这样,您就不必担心处理迭代和while循环所具有的可能的无限循环。

此外,我个人不喜欢在while/foreach中进行函数调用和赋值。。在声明之前多加一行没什么大不了的。将提高可读性,并使调试代码变得更容易。