Reputation: 1434
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?
Upvotes: 2
Views: 57
Reputation: 8613
You could write your own error handler to catch the exception as you want to.
function errorHandler($errno, $errstr, $errfile, $errline) {
if ( E_RECOVERABLE_ERROR===$errno ) {
echo "'catched' catchable fatal error\n";
throw new Exception();
}
return false;
}
set_error_handler('errorHandler');
$t = new DateTime();
try{
$table = "<td>".$t."</td>";
}catch(Exception $e){
$table = "<td>".$t->format("Y-m-d H:i:s")."</td>";
}
echo $table;
This way an exception is thrown that you can catch. It would output
'catched' catchable fatal error
<td>2016-07-14 12:57:27</td>%
Upvotes: 1
Reputation: 371
You can check whether its a date time object using is_a function and handle it
if (is_a($res[$i][$j], 'DateTime')) {
// handle code
}
Upvotes: 2