As title states, my objective is to produce an HTML table using data from a MySQL database.
The general method I am using is sound, as I have written manually a series of cells, but I am trying to scale it to include large numbers of fields, and as such am trying to write the HTML for the cells using PHP and foreach loops with arrays. I’ve written out the context and steps of my working to both give context to my problem and provide general help to people in a similar situation. I know, however, that the problem I have lies specifically in one section of code – indicated clearly below if you want to skip right to it.
Step 1 define arrays for the titles I’d like the fields to have and the column names in the MySQL db:
$titles = array('Name', 'Age', 'Height', 'Weight');
$headers = array('q1', 'q2', 'q3', 'q4');
Step 2: connect to the database ($username and $password previously defined):
try {
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->exec("SET CHARACTER SET utf8");
Step 3: Create my SQL statement via a few concatenations, and fetch the $result:
$sql ="SELECT";
foreach(array_combine($headers, $titles) as $header => $title) {
$sql .= "`$header` AS `$title`,";
}
$sql .= "`q5` AS `Eye Color`";
$sql .= "FROM samdata.CO_data";
$result = $pdo->query($sql);
Step 4: Create $html_table by concatenating static HTML and the results from the above SQL query
if($result !== false) {
$html_table = '<table><tr>';
foreach($titles as $title) {
$html_table .= "<th> $title </th>";
}
$html_table .='</tr> <tr>';
//*********PROBLEM SECTION BELOW **************************
foreach(array_combine($result, $titles) as $row => $title) {
$html_table .= "<td>' .$row\['$title'\]. '</td>";
}
}
//*********PROBLEM SECTION ABOVE **************************
$html_table .= '</tr> </table>';
$conn = null;
echo $html_table;
}
I know the problem lies with the section indicated, because I’ve test all the other parts, and if instead of combining arrays / foreach loops I manually write out, for example:
foreach($result as $row) {
$html_table .= '
<tr>
<td>' .$row['Names']. '</td>
<td>' .$row['Age']. '</td>
<td>' .$row['Height']. '</td>
</tr>';
}
In place of the loop, then it works fine and displays the data for each result for those headings, the problem being I have hundreds and want to be more elegant (and lazy) than writing them all out one by one!
Where am I going wrong? Many thanks in advance for your help.
Your are not looping correctly. $result is a PDOStatement which you must fetch. Try