Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if mysql_query() fails, what to do?

Sometimes so happens that mysql_query() fails to INSERT data and I am unaware of it. So, the question is how do I know when it happens?

like image 433
Wohell Avatar asked Mar 10 '10 04:03

Wohell


People also ask

What will be the return value of mysql_query () function on error?

Return Values ¶ For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or false on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns true on success or false on error.

What is the use of mysql_query () function?

mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.

How many parameters does the mysql_query () function accept?

PHP uses mysqli query() or mysql_query() function to insert a record into a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

How can you retrieve a string containing an error message when a MySQL error occurs?

Description ¶ 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.


1 Answers

Quoting the documentation page of mysql_query :

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

So, to detect whether there's been an error or not, you have to test the return value of your call to mysql_query :

$result = mysql_query('...');
if ($result === false) {
    // And error has occured while executing
    // the SQL query
}


Then, what can you do ?

  • Well, first, you can log the error to a file, that you can analyse later
    • For than, you can use mysql_error and mysql_errno.
  • And you can display a nice error message the user
    • i.e. some kind of "oops, an error occured page".

Remember, though : the user doesn't need to know (and will not understand) the technical error message -- so don't display it.

like image 143
Pascal MARTIN Avatar answered Nov 07 '22 00:11

Pascal MARTIN