HowToPlaza.com

How to wisdom from across the Internet — want to know how to do something? You may find the solution here.


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.


Technorati Tags: ,
AddThis Social Bookmark Button

Posted by admin | Tags: Database, Programming


You can leave a response, or trackback from your own site.

3 Responses to “How to handle MySQL errors in php”

  1. Eric Says:

    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!

  2. Amrit Says:

    Hello Eric.

    I totally agree, but this is just for debugging.

  3. Joseph Says:

    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;
    }

Leave a Reply