Illegal String Offset within PDO For Each loop

浪尽此生 提交于 2019-12-30 04:53:09

问题


PHP Query:

<?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 />";
    }

?>

The two rows that should be printed (timestamp):

What actually prints: 1188((22

The error within the console: PHP Warning: Illegal string offset 'timestamp' in /Sites/pages/user_account.php on line 73 - Line 73 being the echo $row... inside the forloop.

Any help would be greatly appreciated.


回答1:


You are using fetch, which retrieves a single row, instead of fetchAll:

$rows = $query->fetchAll();



回答2:


You have two rows (user_id = 8)

$rows = $query->fetchAll();

For all rows

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

For 1 row , all column

while ($row = $rows) {

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

}


来源:https://stackoverflow.com/questions/15212008/illegal-string-offset-within-pdo-for-each-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!