In php sometimes when you execute MySQL commands the queries don’t execute well and you don’t even know unless you define some mechanism to trap the resulting MySQL error. For instance if you’re in setting a new record into MySQL table and if there is some column mismatched you won’t be able to know it unless you specifically checked the database to see whether a record has been inserted or not. There is a way you can trap whether an error occurred and then take the appropriate steps. This is now you can see if an error has occurred (please remember we are talking about php here so we will be using the php MySQL commands to manipulate MySQL tables):
<?php
if(mysql_errno()>0)
{
// take care of the error.
}
?>
The error descriptions of MySQL are not very helpful so along with seeing the error message you should also see the query in case it is being dynamically generated for instance an online form. In the example below we will use a simple query:
<?php
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$query=mysql_query("insert into mytable (first_name, last_name) values (’" . $fname . "’, ‘" . $lname . "’");
if(mysql_error()>0)
{
print mysql_error() . "<br><br>";
print $query;
}
?>
In the above example in case there is an error in the dynamically generated MySQL query it will not only print the error it will also print the dynamically generated query.
Technorati Tags: php errors, MySQL errors
Share



{ 3 comments… read them below or add one }
This is just an example of how it can be done, but showing your queries to the user is one thing you should NOT DO!!! instead email it or save your errors to an file!
Hello Eric.
I totally agree, but this is just for debugging.
How do you prevent this error from showing up on the web page? In the above example, if you have a bad table name, mysql will throw the error even before the code block:
if(mysql_error()>0)
{
print mysql_error() . “”;
print $query;
}