I am using PHP loops to populate an HTML table from a MySQL database. I have used PDO to fetch the results of a SQL query into $result:
$result = $pdo->query($sql);
(where $sql is a SELECT query)
I am then building an HTML table like this:
if($result !== false)
{
$html_table = '
<table border="1" cellspacing="0" cellpadding="2">
<tr>';
foreach($titles as $title)
{
$html_table .= "<th> $title </th>";
}
$html_table .='</tr> <tr>';
foreach( $result->fetchAll() as $row )
{
$html_table .= '<tr>' . "\n";
foreach( $row as $col )
{
$html_table .= '<td>' .$col. '</td>';
}
$html_table .= '</tr>' . "\n";
}
}
The idea being to get each record in $result, define them as an array called $row then loop through each record and build the table that way.
The problem is, the table is coming out incorrectly – I can’t discern a pattern, but several cells are repeated, (identical data appears side by side) sporadically.
Any idea where I am going wrong here? Thank you.
Figured this one out! 🙂
I’ll post my solution here for others in case it helps.
The issue is the different ways you can fetchAll in PDO. In my code above I am simply using the default fetchAll()
Which produces and array of arrays like this:
Notice that for each column name there are TWO entries, one for the name and one for the indexing number (not sure if that’s the right term, but you can see what’s going on).
For my purposes I needed one entry per column so switch to:
Which gives this array:
And fixed my issue.