So, I have an SQL
query result loaded into an array
. Now, I want to display it in a html
table. This the code I used to use.
$table = "<table><thead><tr><th>".implode('</th><th>', array_keys(current($res)))."</th></tr></thead><tbody>";
for($i = 0; $i < count($res); ++$i) {
$table .= "<tr>";
for($j = 0; $j < count($res[$i]); ++$j) {
$table .= "<td>".$res[$i][$j]."</td>"; //here is the issue if it's date
}
$table .= "</tr>";
}
$table .= "</tbody></table>";
echo $table;
If a certain value is Date
or DateTime
then I get the error Catchable fatal error: Object of class DateTime could not be converted to string
.
Here is my next step which is causing the exact same error. I don't really understand why.
$table = "<table><thead><tr><th>".implode('</th><th>', array_keys(current($res)))."</th></tr></thead><tbody>";
for($i = 0; $i < count($res); ++$i) {
$table .= "<tr>";
for($j = 0; $j < count($res[$i]); ++$j) {
try {
$table .= "<td>".$res[$i][$j]."</td>"; //the issue is here again, so try doesn't seem to work as expected
}
catch (Exception $e){
$table .= "<td>".$res[$i][$j]->format('Y-m-d H:i:s')."</td>";
}
}
$table .= "</tr>";
}
$table .= "</tbody></table>";
echo $table;
So, let's say I want to write a general function for any query result in which I can't tell in advance what record has what type. How can I prepare the code to handle dates?