2016-05-01 77 views
0

因此,我想拉HEADLINES ..我已经保存在一个数据库中,他们都有唯一的ID ..我需要一种方式能够调用它们,但类型或ID为例。While语句

$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()

+0

的'while'通过所有记录中,其中'type'是'sports'循环。在数据库级执行不会产生相同的结果?也许你正在寻找'distinct'或'group by' .. – chris85

+0

就像一个侧面说明,你可以做'<?php while(..):?>'(注意':'而不是'{',并且使用'<?php endwhile;?>'而不是'}来关闭循环 - 当模板化时可以更好一些和更清晰! – Atticus

回答

-1

你为什么不只是使用foreach IM?这样你就不必担心处理迭代和while循环可能出现的无限循环。

此外,我个人更喜欢不在一段时间/ foreach中进行函数调用和赋值。在声明之前添加一行额外行并不是什么大事。将提高可读性并使其更易于调试您的代码。

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 } ?> 
+0

foreach不起作用...我得到Parse错误:语法错误,意外' 'in /nfs/c11/h05/mnt/=/domains/concept/html/temp3/.php on line 121我甚至不能更正它 – KevinM1990112qwq

+0

我也刚刚得到这个致命错误:调用未定义的方法PDOStatement :: bind_result( )在/ nfs/c11/h05/mnt //域名/概念/ html/temp3 /第18行 – KevinM1990112qwq

+0

Aww刚刚意识到你给我的代码是在老的不安全的Mysqli中...请,我的代码在PDO中。 – KevinM1990112qwq