PHP MySQL error handling
To prevent the rest of the script running I need to add exit; or die() . Is there any way to do that using the inline approach as above or do I need to use:
$result = mysql_query($sql); if (!result) < header("Location: /error"); exit(); >
4 Answers 4
function customDie($location) < header('Location: ' . $location); exit(); >mysql_query($sql) or customDie("/error");
If you insist on doing things this way it is better to make a custom query method which handles all this. Something like
function custom_mysql_query($query) < $doDebug=true; // Set to true when developing and false when you are deploying for real. $result=mysql_query($query); if(!$result) < if($doDebug) < // We are debugging so show some nice error output echo "Query failed\n
$query\n"; echo mysql_error(); // (Is that not the name) > else < // Might want an error message to the user here. >exit(); > >
Then just call custom_mysql_query instead of mysql_query then you will always die if a query fails and if $debug is true, you will also get the query which failed and the database error.
But really: You should NEVER use mysql_query or functions which call it(Such as the one I just wrote). It is far too unsafe to ever be used. (Far too difficult to avoid sql injections)
Use the pdo classes instead of the mysql_ methods(Google it, there are many tutorials and explanations online).
mysql_error
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno() ), so if you want to use it, make sure you check the value before calling another MySQL function.
Parameters
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values
Returns the error text from the last MySQL function, or » (empty string) if no error occurred.
Examples
Example #1 mysql_error() example
$link = mysql_connect ( «localhost» , «mysql_user» , «mysql_password» );
?php
mysql_select_db ( «nonexistentdb» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ). «\n» ;
mysql_select_db ( «kossu» , $link );
mysql_query ( «SELECT * FROM nonexistenttable» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ) . «\n» ;
?>
The above example will output something similar to:
1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
See Also
User Contributed Notes 14 notes
If you want to display errors like «Access denied. «, when mysql_error() returns «» and mysql_errno() returns 0, use $php_errormsg. This Warning will be stored there. You need to have track_errors set to true in your php.ini.
Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says: «Errors coming back from the MySQL database backend no longer issue warnings.» Which is not true.
Using a manipulation of josh ><>‘s function, I created the following. It’s purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman’s escape_data() as well since I use it in q().
function escape_data ( $data ) <
global $dbc ;
if( ini_get ( ‘magic_quotes_gpc’ )) <
$data = stripslashes ( $data );
>
return mysql_real_escape_string ( trim ( $data ), $dbc );
>
function q ( $page , $query ) <
// $page
$result = mysql_query ( $query );
if ( mysql_errno ()) <
$error = «MySQL error » . mysql_errno (). «: » . mysql_error (). «\n
When executing:
\n $query \n
» ;
$log = mysql_query ( «INSERT INTO db_errors (error_page,error_text) VALUES (‘ $page ‘,'» . escape_data ( $error ). «‘)» );
>
>
// Run the query using q()
$query = «INSERT INTO names (first, last) VALUES (‘myfirst’, ‘mylast'» );
$result = q ( «Sample Page Title» , $query );
?>
Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.
Just spent a good 30 minutes trying to figure out why i didn’t see my SQL errors.
When creating large applications it’s quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.
This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.
The script writes a log file in directory ( in this case /log ) as well.
The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.
$system_operator_mail = ‘developer@company.com’ ;
$system_from_mail = ‘info@mywebsite.com’ ;
function db_query ( $query ) global $b_debugmode ;
// Perform Query
$result = mysql_query ( $query );
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (! $result ) if( $b_debugmode ) $message = ‘Invalid query:
‘ . mysql_error () . ‘
‘ ;
$message .= ‘Whole query:
‘ . $query . ‘
‘ ;
die( $message );
>
raise_error ( ‘db_query_error: ‘ . $message );
>
return $result ;
>
function raise_error ( $message ) global $system_operator_mail , $system_from_mail ;
$serror =
«Env: » . $_SERVER [ ‘SERVER_NAME’ ] . «\r\n» .
«timestamp: » . Date ( ‘m/d/Y H:i:s’ ) . «\r\n» .
«script: » . $_SERVER [ ‘PHP_SELF’ ] . «\r\n» .
«error: » . $message . «\r\n\r\n» ;
// open a log file and write error
$fhandle = fopen ( ‘/logs/errors’ . date ( ‘Ymd’ ). ‘.txt’ , ‘a’ );
if( $fhandle ) fwrite ( $fhandle , $serror );
fclose (( $fhandle ));
>
// e-mail error to system operator
if(! $b_debugmode )
mail ( $system_operator_mail , ‘error: ‘ . $message , $serror , ‘From: ‘ . $system_from_mail );
>
some error can’t handle. Example:
ERROR 1044: Access denied for user: ‘ituser@mail.ramon.intranet’ to database ‘itcom’
This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = «» .
My suggested implementation of mysql_error():
$result = mysql_query($query) or die(«A fatal MySQL error occured.\n
Query: » . $query . «
\nError: (» . mysql_errno() . «) » . mysql_error());
This will print out something like.
A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong
It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.
When dealing with user input, make sure that you use
echo htmlspecialchars ( mysql_error ());
?>
instead of
echo mysql_error ();
?>
Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.
Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?
Oops, the code in my previous post only works for queries that don’t return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):
function myquery ($query) $result = mysql_query($query);
if (mysql_errno())
echo «MySQL error «.mysql_errno().»: «.mysql_error().»\n
When executing:
\n$query\n
«;
return $result;
>
A friend of mine proposed a great solution.
$old_track = ini_set ( ‘track_errors’ , ‘1’ );
if ( $this -> db_handle != FALSE && $db_selection_status != FALSE )
$this -> connected = 1 ;
ini_set ( ‘track_errors’ , $old_track );
>
else
$this -> connected =- 1 ;
$mysql_warning = $php_errormsg ;
ini_set ( ‘track_errors’ , $old_track );
throw new mysql_cns_exception ( 1 , $mysql_warning . » » . mysql_error ());
>
?>
My suggested implementation of mysql_error():
$result = mysql_query($query) or die(«A fatal MySQL error occured.\n
Query: » . $query . «
\nError: (» . mysql_errno() . «) » . mysql_error());
This will print out something like.
A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong
It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.
«Errors coming back from the MySQL database backend no longer issue warnings.» Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host ‘locallllllhost’ (11001)
That’s a warning, which is not trapped by mysql_error()!
This is a big one — As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I’m still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():
MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client
According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:
Set PASSWORD for ‘user’@’host’ = OLD_PASSWORD(‘password’);
PHP checking if query returns anything error
I’ve been pondering about this for a while, I’m trying to see if the query wields any results and I want to do something if it doesn’t return any results. PHP:
$json = $_REQUEST['json']; $json = stripslashes($json); $jsonobj = json_decode($json); $me = $jsonobj -> me; $other = $jsonobj -> other; mysql_select_db("tinyspace", $con); $result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')"); if(mysql_num_rows($result) > 0)
5 Answers 5
just to be sure, how many columns do you have named userid ? user_id, user_id1, user_id2 ? do you mean user_id1 in place of user_id in the below line, by any chance?
$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
If so, maybe thats why you aren’t fetching any results.
$result = mysql_query("SELECT * FROM friends WHERE (user_id1 = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
the question asks how to check whether the query returns no results, this answer doesn’t satisfy the question, it should be posted as a comment
for those who think my answer is incorrect or the opposite of what is asked, please read the question from the beginning again, very carefully.
Shouldn’t this be if ($result) instead of the opposite? The else ends up being «if result is false is not true» which is nothing short of confusing.»
the person who asked the question said they wanted to do something if the result returned nothing, this way when the query fails or yields nothing, you can add your code in there, hence my answer
mysql_num_rows() is okay to use for checking if you have results, and should work in your example..
However, if your call to mysql_num_rows() doesn’t work as expected (i.e. always false), it’s almost always down to a problem with the query. mysql_num_rows() expects a result resource, and if there is a problem with your query, mysql_query will return a false.
You can amend your mysql_query() call to
mysql_query("sql here") or die(mysql_error());
That should give you an idea if the error lies in the query. Once you’ve checked your query is working as expected, your mysql_num_rows() will start functioning correctly.