【问题标题】:PDO while loop returning only one rowPDO while 循环仅返回一行
【发布时间】:2013-08-07 08:36:56
【问题描述】:

我已经为 PDO while 循环尝试了几种不同的版本,但它们都没有返回超过一行。问题在于循环中对dreamyPrizes 表的调用。如果我把它拿出来,它可以正常工作,它只返回一行。

我试过了:

  $st = $db->prepare("SELECT * FROM `dreamyAuctions` WHERE `showOnHomePage` =:yes AND `active`=:yes AND `completed`=:no ORDER BY `StartDate`"); // need to filter for next auction
$st->bindParam(':yes', $yes); // filter
$st->bindParam(':no', $no); // filter
$st->bindParam(':gameId', $gameId); // filter
$yes=1;
$no=0;
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);

<? 
while($r = $st->fetch(PDO::FETCH_ASSOC)){?>
<?
$auctionId= $r['id'];

$startDate = date("m-d-Y h:i A", strtotime($startDate));

if (strlen($title) > 100)
$title = substr($title, 0, 90) . '...</a>';

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$st = $db->prepare("SELECT * FROM `dreamyPrizes` WHERE `id`=:prizeId"); // need to    filter for next auction
$st->bindParam(':prizeId', $prizeId); // filter
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
$prizeImage= $r['image1'];
$retailPrice= $r['retailPrice'];
 ?> 

 <div>div to loop</div> <? }?>

我也试过了

do {

$auctionId= $r['id'];

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$st = $db->prepare("SELECT * FROM `dreamyPrizes` WHERE `id`=:prizeId"); // need to filter for next auction
$st->bindParam(':prizeId', $prizeId); // filter
$st->execute();
$rs = $st->fetch(PDO::FETCH_ASSOC);
$prizeImage= $rs['image1'];
$retailPrice= $rs['retailPrice'];

?>
<div>div to loop</div>
<?php } while ($r = $st->fetch(PDO::FETCH_ASSOC)); ?> 

【问题讨论】:

  • 1.在第一个查询中去掉无用的参数。使用 JOIN 在 one 查询中完成所有操作。 3. 总是在你的脚本中有error_reporting(E_ALL)

标签: php pdo


【解决方案1】:

必须将第二个表中的“st”更改为“sts”才能正常工作

$sts = $db->prepare("SELECT * FROM `dreamyPrizes` WHERE `id`=:prizeId"); // need to filter    for next auction
$sts->bindParam(':prizeId', $prizeId); // filter
$sts->execute();
$rs = $sts->fetch(PDO::FETCH_ASSOC);
$prizeImage= $rs['image1'];
$retailPrice= $rs['retailPrice'];`enter code here`

【讨论】:

  • 仍然 $prizeId 不知从何而来
  • 哇,我的代表被这篇文章打败了。你们知道我工作了多长时间才让它起作用吗?
【解决方案2】:
$sql = "SELECT p.* FROM `dreamyAuctions` a JOIN `dreamyPrizes` p 
        ON p.id = a.id
        WHERE `showOnHomePage` = 1 AND `active`= 0 AND `completed`= 0 
        ORDER BY `StartDate`";
$stm = $db->query($sql);
$data = $stm->fetchAll();

这就是您获取数据所需的全部内容。
现在您可以继续从分离的模板输出

<? foreach ($data as $row): ?>
<div>div to loop <?=$row['image1']?> <?=$row['retailPrice']?></div>
<? endforeach ?>

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 2023-03-16
    • 2016-05-22
    • 2018-03-02
    • 2018-07-11
    • 2017-04-17
    • 2012-04-04
    • 2015-11-17
    相关资源
    最近更新 更多