MySQLi Tutorial: Debugging with MySQLi

There will be times when you run into problems with your MySQL statements or connections, there are ways to help you sort out what went wrong, I’ll cover that in this tutorial.

If you ever get an error like these:
Access denied for user ‘username’@’localhost’ (using password: YES)
Unknown database ‘phpmysqlitutorial’

They can be easily solved by double checking your connection details and verifying your database name using a tool such as phpMyAdmin or if your hosting provides it, the MySQL administration tools in CPanel.

I’ll start with showing you how to check for errors on your connection. You’ll need two functions:

mysqli_connect_errno() - Returns an error code
and
mysqli_connect_error() - Returns a string description of the last error
                         produced by your connection
<?php
/* make our connection */
$sql = new mysqli('localhost','username','password','database');
 
/* check for an error code */
if ( mysqli_connect_errno() ) {
    /* oh no! there was an error code, what's the problem?! */
    echo 'There was an error with your connection: '.mysqli_connect_error();
}
 
/* close up */
$sql->close();
?>

If for some reason your queries don’t seem to be inserting, updating, deleting or selecting, you can find out how by using MySQLi’s error properties. You will need:

->errno - Returns the error code of the last error.
and
->error - Returns a string description of that error.
<?php
/* make our connection */
$sql = new mysqli('localhost','username','password','database');
 
/* make a purposely erroneous query, notice there is a missing ' at the end */
$query = "SELECT * FROM `people` WHERE `name`='Mike;";
 
/* try and run this query */
if ( !$sql->query($query) ) {
    echo "Error code ({$sql->errno}): {$sql->error}";
} else {
    echo 'Query was sucessful, proceed.';
}
 
/* alternatively you could shorten that to: */
$result = $sql->query($query) or exit("Error code ({$sql->errno}): {$sql->error}");
 
/* close up */
$sql->close();
?>

And there you have it, two ways to check and make sure your MySQL details and queries run smoothly. So just remember, if you find yourself pulling your hair out because your queries aren’t working, or you connection is failing, print out some errors that can really help you figure out what you might have missed.

Author: Mike on March 31, 2011
Category: MySQLi, Tutorials
Tags: , ,

Comments are closed.

Last articles