Invalid line offset in PDO For each loop

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

?>

Two lines to be printed (timestamp):

Database

What actually prints: +1188 ((22

Error in console: PHP Warning: invalid line offset "timestamp" in / Sites / pages / user _account.php on line 73 - line 73 is an echo line ... inside the fork.

Any help would be greatly appreciated.

+5
source share
2 answers

You use fetchone that retrieves one row instead fetchAll:

$rows = $query->fetchAll();
+8
source

You have two lines (user_id = 8)

$rows = $query->fetchAll();

For all lines

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

For 1 row, the entire column

while ($row = $rows) {

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

}
-1
source

All Articles