0Hmm

How to handle MySQL errors in php

by Sarah Watts on June 14, 2008


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: ,
  • Stumbleupon
  • Delicious
Share

Related posts

  • No Related Post

{ 3 comments… read them below or add one }

Eric June 29, 2008 at 1:42 am

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!

Amrit June 30, 2008 at 7:54 am

Hello Eric.

I totally agree, but this is just for debugging.

Joseph October 7, 2008 at 8:32 am

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 Comment

Previous post: How to wake-up early in the morning

Next post: How to host your files for free