php - Codeigniter how to get DB errors using hooks and save in logs table?
Get the solution ↓↓↓I need to save all PHP and Database errors in log table in codeigniter. For this i am trying to do this using hooks in codeigniter. This is my code.
hooks.php
$hook['post_controller'] = array(
'class' => 'Db_log',
'function' => 'logQueries',
'filename' => 'db_log.php',
'filepath' => 'hooks'
);
Codeigniter how to get DB errors using hooks and save in logs table
I have created file db_log.php in hooks directory. and this is my code.
<?php
class Db_log {
function __construct() {
}
function logQueries() {
$CI = & get_instance();
$times = $CI->db->query_times;
$error = $CI->db->error();
print_r($error);
// foreach ($CI->db->queries as $key => $query)
// {
// $sql = $query . " \n Execution Time:" . $times[$key];
// }
}
}
It's working to show all queries but not working when any error comes related to Database. I had tried $CI->db->error() also to get the error but it's not working. I need to show custom message if any error come related to Database and need to save a entry in custom log table.
Try with shutdown_function
public function setHandler() {
register_shutdown_function('handleShutdown');
}
}
function handleShutdown() {
print_r(error_get_last());
if (($error = error_get_last())) {
die("nnnnnnnnnnnnn");
ob_start();
echo "<pre>";
var_dump($error);
echo "</pre>";
$message = ob_get_clean();
//sendEmail($message);
ob_start();
echo '{"status":"error","message":"Internal application error!"}';
ob_flush();
exit();
}
}
hooks.php
$hook['pre_system'][] = array(
'class' => 'PHPFatalError',
'function' => 'setHandler',
'filename' => 'PHPFatalError.php',
'filepath' => 'hooks'
);
Answer
Solution:
I think it's impossible - its one of the flaws in CI < 4
The problem is in their db driver class - if you take a look at their display_error() function you'll see everytime a DB Error occurs the entire application will be stopped immediately.
However you can try to register a shutdown function and try to handle some stuff there.
Another method would be to extend the DB Driver - for that purpose you've to extend the Loader.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string deprecated
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.