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.