mysql_error() Function in PHP
What is mysql_error() function in PHP?
How does mysql_error() works?
Explanation
mysql_error() function returns the text error message from previous MySQL operation.
Syntaxstring mysql_error ( [resource link_identifier])
Returns the error text from the last MySQL function, or '' (the empty string) if no error occurred.
mysql_error() function is used to retrieve the error text from the most recently executed MySQL function
Example:
<?php //Attempt to connect to the default database server $link = mysql_connect("mysql_host", "mysql_user", "mysql_password") or die ("Could not connect"); //select non existing database if (!mysql_select_db("my_database", $link)) { //prints error message on selecting non existing database echo mysql_errno($link) . ": " . mysql_error($link). "n"; } //Attempt to select database mysql_select_db("my_database", $link); //Execute query if (!mysql_query("SELECT * FROM nonexistenttable", $link)) { //Display error report echo mysql_errno($link) . ": " . mysql_error($link). "n"; } mysql_close($link); ?> |
In the above example, the query fails due to non existance of database 'my_database' and table 'nonexistenttable'. Here 'mysql_errno' function prints the occured error number and 'mysql_error' prints the text error message from the executed query.
RESULT:
1049: Unknown database 'nonexistentdb'
1146: Table 'my_database.nonexistenttable' doesn't exist
See also: mysql_errno() and MySQL error messages