I am new to PHP.
I am trying to display the details of employees in form of table.
But while($row = $result->fetchObject())
part is not executing, as $
PDO's documentation is a little confusing on this, but the PDOStatement::fetch() method and its cousin fetchAll()
return false
when no more rows are available to return. The docs say it returns false
on failure, and a lack of available rows counts as a failure.
Your initial call to fetchAll()
gets all the rows from the PDOstatement
result object and there are no more for the fetchObject()
call to retrieve so it returns false
.
You only need your initial call to fetchAll()
, but you may need to set its fetch type to PDO::FETCH_OBJ
if you did not previously set the default fetch type for your connection.
Then, you can replace your while
loop with a simple foreach
loop over the $rows
array you already have. This has the added benefit of separating your display logic from your database query business logic a little more:
if ($result = $pdo->query($sql)) {
// Fetch them now, as objects
$rows = $result->fetchAll(PDO::FETCH_OBJ);
$num_rows = count($rows);
if ($num_rows > 0) {
echo "<table>\n";
echo " <tr class=\"heading\">\n";
echo " <td>ID</td>\n";
echo " <td>Name</td>\n";
echo " <td>Designation</td>\n";
echo " </tr>\n";
// $rows now has everything you need, just loop over it
foreach ($rows as $row {
echo " <tr>\n";
echo " <td>" . htmlspecialchars($row->id) . "</td>\n";
echo " <td>" . htmlspecialchars($row->name) . "</td>\n";
echo " <td>" . htmlspecialchars($row->designation) . "</td>\n";
echo " </tr>\n";
}
echo "</table>";
} else {
echo "No employees in database.";
}
else {
echo "ERROR: Could not execute $sql. " . print_r
($pdo->errorInfo());
}
Note also, that I added calls to htmlspecialchars()
while writing output to HTML. That is always recommended, so that characters like < > &
which have special meaning in HTML are properly encoded, and avoids cross-site scripting vulnerabilities if those values originated as user input.