I am constructing a PHP application and I want to be able to log every sql queries in the site. Therefore, I wrote a function to execute the sql queries and log the information. The problem I have now is that for some reason, the only time where the query runs successfully is when it is returned. But it does not seem to work within the function itself. $conn->error always remains empty. Indicating that that the query ran successfully. But if ($conn->query($query) !== TRUE)
returns FALSE. Any help would be much appreciated.
Here is my function where $conn is my sql connection, $site is the site settings and $alerts contains all the errors that may occur on the site.:
function SQLLogger($query,$username = null){
global $conn,$site,$alerts;
if($username == null){$username=$_SESSION[$site['id']];}
if(strpos($query, 'INSERT INTO') !== false){
$action = "inserting";
} elseif(strpos($query, 'UPDATE') !== false){
$action = "updating";
} elseif(strpos($query, 'SELECT') !== false){
$action = "selecting";
} elseif(strpos($query, 'DELETE') !== false){
$action = "deleting";
}
if ($conn->query($query) !== TRUE){
$status = "Error";
$error = array(
'type' => 'error',
'title' => 'Logger has reported an error',
'body' => 'Error '.$action.' row: '.$conn->error,
);
array_push($alerts,$error);
} else {
$status = "Success";
}
$ip = $_SERVER['REMOTE_ADDR'];
$query2 = "INSERT INTO logs (created, modified, `user`, `query`, `error`, `action`, `status`, `ipv4`) VALUES ( '".date("Y-m-d H:i:s")."', '".date("Y-m-d H:i:s")."', '".$username."', '".str_replace("'", "\\'", $query)."', '".$conn->error."', '".$action."', '".$status."', '".$ip."' )";
if ($conn->query($query2) !== TRUE) {
$error = array(
'type' => 'error',
'title' => 'Logger has reported an error',
'body' => 'Error inserting row: '.$conn->error,
);
array_push($alerts,$error);
}
return $conn->query($query);
}