Home » Database » How to handle MySQL errors in php

How to handle MySQL errors in php



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.

[tags]php errors, MySQL errors[/tags]