【问题标题】:Illegal String Offset within PDO For Each loopPDO For Each 循环中的非法字符串偏移
【发布时间】:2013-02-19 03:47:29
【问题描述】:

PHP 查询:

<?php

    $query = $db->prepare('SELECT * FROM Locations WHERE user_id = :id LIMIT 0, 5');
    $query->bindParam(":id",$id);
    $result = $query->execute();

    $rows = $query->fetch();

    foreach ($rows as $row) {
        echo $row["timestamp"]; "<br />";
    }

?>

应该打印的两行(时间戳):

实际打印的内容: 1188((22

控制台中的错误: PHP 警告:第 73 行 /Sites/pages/user_account.php 中的非法字符串偏移 'timestamp' - 第 73 行是 forloop 内的 echo $row...。

任何帮助将不胜感激。

【问题讨论】:

  • 使用fetchAll 而不是fetch
  • @A.Rodas,完美,谢谢!
  • 不客气。根据this suggestion,我会将我的评论作为答案发布,因此您可以根据需要将其标记为正确。

标签: pdo foreach


【解决方案1】:

您使用的是fetch,它检索单行,而不是fetchAll

$rows = $query->fetchAll();

【讨论】:

    【解决方案2】:

    你有两行 (user_id = 8)

    $rows = $query->fetchAll();
    

    对于所有行

    foreach ($rows as $row) {
      echo $row . "<br />";
    }
    

    对于 1 行,所有列

    while ($row = $rows) {
    
      foreach ($row as $column) {
        echo $column . "<br />";
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 2019-03-01
      • 2017-06-14
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      相关资源
      最近更新 更多