Environment – PHP5.2.17, MySQL5.0.92
I am implementing an error logging framework in my application and I am trying to log errors and warnings to a database.
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
I wanted to test the logging and passed the wrong host to the mysql_connect function. As expected I got the warning on screen
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'host' (1) in /path/to/my/php/file.php on line 4
And my log function was called but mysql_error() is null. According to the php manual (http://php.net/manual/en/function.mysql-connect.php), mysql_error() should return the last mysql error. In the manual they even have an example of how to echo the error to the screen using mysql_error().
I tried using mysql_error($db), but it returns an error stating that $db is not defined.
I tried replacing my function with echo mysql_error(); and I doesn’t show anything.
I tried using mysql_errno(); and I get null also.
I know the script is catching the warning because it is outputting it to the screen.
One way to resolve my problem is to store the warning in a variable.
I appreciate any help anyone can provide. Thank you.
UPDATE – 2 SOLUTIONS:
SOLUTION 1: (thank you to Mario for suggesting this in one of his comments to this post)
Use PHP function error_get_last() – reference (http://php.net/manual/en/function.error-get-last.php).
New working code with this solution:
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
$error = error_get_last();
log($error['type'] . ": " . $error['message'] . " in file " . $error['file'] . " on line " . $error['line']);
}
...continue code
SOLUTION 2: (thank you to PauPRO for suggesting this in answer 1 below)
Before using $php_errormsg, we need to set track_errors to 1 in the php.ini file. Just include the following line in your php.ini file
track_errors = 1
Alternatively you can set track_errors to 1 inside the script see below the code with this alternative:
ini_set('track_errors', 1);
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
Both solutions work!!!
Make sure you turn on
track_errorsbefore using$php_errormsg: