MySQLi Tutorial: Prepared Statements

Here I’ll cover the basics of using a prepared statement with MySQLi in PHP. I’ll be using the same table as this tutorial. Let’s begin, shall we?

/* make the connection */
$sql = new mysqli('localhost','username','password','database');
/* we'll look for Mike */
$findname = 'Mike';
/* make sure we can prepare the statement */
if ( $prep = $sql->prepare("SELECT * FROM `people` WHERE `name`=?") ) {
    /* first we want to bind $findname to the first ? in our statement
    since it is a string, we'll use 's' */
    /* execute the statement */
    /* bind our results to some useable variables
    you want to bind these in the order of the columns
    in your table, in our case: id, name, age */
    /* now we want to fetch the data from the database */
    /* the order in which you want the variables displayed
    is the order in which they go after the statement */
    printf("row id is: %d, %s is %d years old.",$id, $name, $age);
    /* close the statement */
} else {
    echo "There was a problem preparing your statement";
/* close up */

And there you have it, a very basic, introduction to prepared statements using MySQLi. I hope you found it useful.

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

Comments are closed.

Last articles