【问题标题】:Returning an array with PDO - using FetchAll doesn't work使用 PDO 返回数组 - 使用 FetchAll 不起作用
【发布时间】:2014-06-29 01:12:17
【问题描述】:

我使用以下代码从我的数据库中检索数据。问题是它只显示第一行。在这种特殊情况下,这意味着网页上只显示第一张图片,但我想显示所有图片。

<?php 
    $sql = "SELECT `image-id`, `article-id`, `image-path`, `image-title` FROM `table-images` WHERE `article-id` = :id";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(":id", $id);
    $stmt->execute();

    if($result = $stmt->fetch(PDO::FETCH_ASSOC))
    {
?>

<a class="swipebox" href="<?php echo $result['image-path'];?>" title="<?php echo $result['image-title'];?>">
<img alt="image" src="<?php echo $result['image-path'];?>"></a>

<?php
    }// end if
    else {
    echo '0 results';
    }// end else
?>

我阅读了 this article 所以我尝试使用代码:

if($result = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC));?

...但这不起作用。它甚至不再呼应第一张照片。我在这里错过了什么?

【问题讨论】:

  • 使用while 循环。编辑:我正要提到一个foreach 循环,就像答案出现在下面一样。
  • while ($arr = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) { echo $arr['name']; } 取自这个答案stackoverflow.com/a/19364078 你有两种方法可以做到这一点。 whileforeach,您可以选择。
  • 解释一下你现在的代码在做什么:你的条件语句正在检查 if 结果是否存在;如果是这样,它只会回显一个结果,因为您不会循环直到它在您的表中找不到任何其他结果。
  • 感谢您的帮助。它适用于 while 循环。

标签: php sql pdo fetch fetchall


【解决方案1】:

这是它的工作原理:

$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$success = $stmt->execute();

if($success){
    //fetch here
}

现在您有 2 个用于获取数据的选项:

fetch()

fetch() 将逐一获取行,因此您需要一个 while 循环。

while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
 // get data
}

fetchAll()

fetchAll() 一次获取所有行,因此无需 for 循环来检索数据,但如果需要循环,则需要 for 循环。

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
  //do something
}

【讨论】:

  • 谢谢。这正是我正在寻找的信息。
【解决方案2】:
<?php 
    $sql = "Your SQL query";
    $id  = 1; 

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(":id", $id);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC)

    if($stmt->rowCount()){

       foreach($result as $row){
         echo $row['row_name'].'<br/>'; 
       }

    }else{
       echo 'No results found'; 
    }

【讨论】:

  • 为了让您的答案正常工作,您需要使用 fetchAll ,我为您修复了它
猜你喜欢
  • 1970-01-01
  • 2014-02-02
  • 2013-02-05
  • 2013-04-21
  • 2014-05-01
  • 2015-03-31
  • 2016-04-16
  • 1970-01-01
  • 2017-06-16
相关资源
最近更新 更多