Selecting table data with PDO statements

You are doing too much actually:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);

The problematic line is:

$result = $dbh->query($query);

Check with http://php.net/pdo.query, the parameter is a string, actually the SQL string you already use above, not the result value of a PDO::prepare() call.

For your simple query you can just do:

$result = $dbh->query("SELECT * FROM students");

Or if you like to prepare:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query;

The later is some boilerplate if you want to insert variables into the query, that's why you prepare it.


The next problem is with the foreach line:

foreach($result as $row);

You are terminating the loop immediately because of the semicolon ; at the end. Remove that semicolon so that the following angle-bracketed code-block becomes the body of the foreach-loop.


Your code is wrong:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);

After executing a prepared statement, you can just call fetchAll() on it:

$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchAll();

The rest of your code will work fine once you remove the semicolon after the foreach.