Prepared SELECT statement Sqlite/PHP

I’m trying to rewrite the following as a prepared statement but I’m getting my proverbials in a twist.

$query = 'SELECT * FROM table WHERE room="'.$room.'" ORDER BY name;';
$result = $db->query($query);
foreach ( $result as $row ) {
  echo '<p>', $row['name'], ' ', $row['comment'], '</p>', "\n";
}

I’ve got as far as

$query = 'SELECT * FROM table WHERE room=:room ORDER BY name;';
$stmt = $db->prepare($query);
$stmt->bindParam(':room', $room);
$result = $stmt->execute();
foreach ( $result as $row ) {
  echo '<p>', $row['name'], ' ', $row['comment'], '</p>', "\n";
}

but I get Invalid argument supplied for foreach(). Can some kind soul tell me where I’m going wrong? I’m happily using prepared statements for DELETEs and INSERTs. :slight_smile:

And how do I test if the results are empty?

$query = 'SELECT * FROM table WHERE room=:room ORDER BY name;';
$stmt = $db->prepare($query);
$stmt->bindParam(':room', $room);
$result = $stmt->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC) {
  echo '<p>', $row['name'], ' ', $row['comment'], '</p>', "\n";
}

Thanks Pepster, having added a missing ) I get
Fatal error: Call to a member function fetch() on a non-object

I have, at last, found the answer:

$query = 'SELECT * FROM table WHERE room=:room ORDER BY name;';
$stmt = $db->prepare($query);
$stmt->bindParam(':room', $room);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ( $result as $row ) {
  echo '<p>', $row['name'], ' ', $row['comment'], '</p>', "\n";
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.