While语句的问题

时间:2016-05-01 04:33:05

标签: php html mysql

所以我试图拉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()

2 个答案:

答案 0 :(得分:0)

请试试这个:

$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 } ?>

答案 1 :(得分:-1)

为什么不用foreach?这样您就不必担心处理迭代以及while循环可能存在的无限循环。

另外,我个人不喜欢在一段时间内进行函数调用和赋值。在声明之前添加1个额外行并不是什么大不了的事。将提高可读性并使代码调试变得更容易。