Steve W Steve W - 1 year ago 81
SQL Question

Extracting multiple rows of data from mysql and formatting in a web page table using PDO

I'm struggling to extract data from a mysql database and present it in a table on a webpage. I'm fairly sure I'm missing something simple but I'm new to this stuff and can't work out what's gone wrong. Here's hoping someone can spot my silly error and let me know!

Code prints the header info in the table OK but i get no rows.

When I've figured it out I plan to strip off the , and tags and use an include on some other pages.


Code below

<!DOCTYPE html>
//database login info
require_once 'dbconfig.php';

try {
//connect to batabase
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//check connection to database. It works OK
echo "Connected to database $dbname at $host successfully. <br>";

$sql = ("SELECT `name`, `comment`, `entered` FROM `comment`");
$result = $pdo->query($sql);
//connection error
catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
<div id="container">
<table width ="100%" border ="1">
<?php while ($row = $result->FetchALL(PDO::FETCH_ASSOC)) {

"<tr> <td>".$row['comment']." </td>
<td>".$row['name']." </td>
<td>".$row['entered']." </td>

Answer Source


returns a PDOStatement object, or FALSE on failure.

S0 no need fetch it twice $result->FetchALL(PDO::FETCH_ASSOC)

Just use foreach loop as

 foreach ($result as $row) {
            "<tr>   <td>".$row['comment']." </td>                   
                    <td>".$row['name']." </td>
                    <td>".$row['entered']." </td>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download