Example: Filtering guests with "Where" using PDO and prepared statement

IdFirstnameLastnameEmail
1JohnDoejohn@example.com
10JohnDoejohn@example.com
15JohnDoejohn@example.com
23JohnDoejohn@example.com
27JohnDoejohn@example.com
32JohnDoejohn@example.com
37JohnDoejohn@example.com
41JohnDoejohn@example.com
49JohnDoejohn@example.com
50JohnDoejohn@example.com
54JohnDoejohn@example.com
59JohnDoejohn@example.com
64JohnDoejohn@example.com

Here is the code for accessing the database and display the information.

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname<</th><th>Lastname</th><th>Email</th></tr>";

class TableRows extends RecursiveIteratorIterator {
  function __construct($it) {
    parent::__construct($it, self::LEAVES_ONLY);
  }

  function current() {
    return "<td style='width:150px;border:1px solid black;background-color:yellow;'>" . parent::current(). "</td>";
  }

  function beginChildren() {
    echo "<tr>";
  }

  function endChildren() {
    echo "</tr>" . "\n";
  }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "DBname";

// Create connection
try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Define and execute prepared statement
  $stmt = $conn->prepare("SELECT id, firstname, lastname, email FROM MyGuests WHERE lastname='Doe'");
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
    echo $v;
  }
} catch(PDOException $e) {
  echo "Error: " . $e->getMessage() . "";
}
$conn = null;
echo "</table>";
?>