Go Back   ClanTemplates > Design > Tutorials
Game Tracker

Tutorials Staff and user-submitted tutorials are posted in here

Reply
  Thread Tools Display Modes
#1  
Old June 1st, 2009, 06:46 PM
Ross Ross is offline
/dev/null
 
Join Date: Mar 2006
From: England
iTrader: (1)
Posts: 6,026
Ross has a reputation beyond repute Ross has a reputation beyond repute Ross has a reputation beyond repute
Send a message via MSN to Ross
Using MySQLi and prepared statements in PHP

This tutorial shows you how to build prepared statements using the MySQL Improved extension, rather than queries you construct yourself. This helps to protect your application from SQL injection as quoting and escaping are done for you, in case you forget to escape on your variables.

The MySQLi class is a core package of PHP5 - if you're running PHP4 you'll need to upgrade to use this. Methods of this class are available in procedural form (functions) if you want to build functionality into a DAL.

Creating a database connection

Firstly, you need to instantiate the MySQLi object with your database credentials. This is easily done:

PHP Code
			
$conn = new MySQLi('localhost''root''password''mydb');

if (!
$conn) {
    die(
"MySQL error: #{$conn->connect_errno}{$conn->connect_error}");

This creates the database link and checks for a connection error.

Creating a prepared statement

Prepared statements are like queries, but without some of the values. These are values that are dynamic to each query. For example, if I had a profile page that gets user information based on a user id (in $_GET['id']) I might have a query like this:

Code
SELECT username, email FROM users WHERE id = $_GET['id'] LIMIT 1
Which I'd query like this (using ext/mysql):

PHP Code
			
$conn mysql_connect('localhost''root''pass');

mysql_select_db($conn'mydb');
if (!
$conn) {
    die(
"MySQL error: #" mysql_errno($conn) . ": " mysql_error($conn));
}

if (!isset(
$_GET['id']) || !is_numeric($_GET['id'])) {
    die(
'Missing/invalid user id');
}

$query 'SELECT username, email FROM users ' 
       
'WHERE id = '
       
mysql_real_escape_string($_GET['id'])
       . 
' LIMIT 1';

$result mysql_query($query);
if (
mysql_num_rows($query) == 0) {
    die(
'No user data found for user ' (int) $_GET['id']);
}
$result mysql_fetch_assoc($query);
echo 
$result['username'] . ' : ' $result['email']; 
It's untidy and mixes validation in with query code which isn't great. Here's the same query using a prepared statement:

PHP Code
			
$query 'SELECT username, email FROM users WHERE id = ? LIMIT 1';

// the query is validated here and will error if it is invalid syntax
$stmt $conn->prepare($query);

// bind the user id as an integer to the first ?
$stmt->bind_param('i'$_GET['id']);
$stmt->execute(); // execute the statement

$stmt->store_result(); // this call is required for the next operation
if ($stmt->num_rows == 0) {
    die(
'No user data found for user ' (int) $_GET['id']);
}

$stmt->bind_result($username$email);
$stmt->fetch();
$stmt->close();

echo 
"$username$email"
This is a bit cleaner (due to the OOP interface I feel) but also allows you more power with less code with the bind_result method. The method's fairly simple: the first parameter is the format - one character for each variable to be replaced, with its data type (s is string, i is int, d is decimal and b for blob (binary data)); the rest of the parameters are the corresponding variables.

PHP Code
			
$query 'SELECT name, age FROM users '

       
'WHERE id = ? OR name LIKE ? OR rating >= ? LIMIT 1';
$stmt $conn->prepare($query);
$stmt->bind_param('isd'1'kalle'2.40); 
Another thing is that variables will be converted to the type you specify; so if you try to convert true to an int it will come out as 1.

When binding the result to variables you can make things much easier with loops too:

PHP Code
			
$stmt->bind_result($name$age$rating);

while (
$stmt->fetch()) {
    echo 
"<tr>"
       
"<td>$name</td>"
       
"<td>$age</td>"
       
"<td>$rating</td>"
       
"</tr>";

When iterating over fetch() each variable is rebound for the current row - similar to mysql_fetch_row but again cleaner.

Conclusion

MySQLi has many nifty features (another to explore is multi_query - allowing you to execute multiple statements (terminated by semicolons) as you would in MySQL) and should be a part of your arsenal if you use PHP with MySQL.
__________________
Quote: Originally Posted by Andy View Post
Tea + Vodka = Ross' tea

Ross = Hardcore

Last edited by Ross : June 1st, 2009 at 09:59 PM Reason: Fix
Reply With Quote
#2  
Old June 1st, 2009, 09:09 PM
Sanesh. Sanesh. is offline
Iownyourmon
 
Join Date: Oct 2004
iTrader: (0)
Posts: 5,969
Sanesh. has a reputation beyond repute Sanesh. has a reputation beyond repute Sanesh. has a reputation beyond repute
Send a message via MSN to Sanesh.
Re: Using MySQLi and prepared statements in PHP

Uh! How did Kalle let you on Dev team with such yucky formatted code?!

Lol, other than that the only problem I noticed was...
PHP Code
			
$stmt $conn->prepare($query); 

Did you mean to write $mysqli instead of $conn? Because I didn't think mysql_connect() returned an object... its been about a year since I touched PHP though so I might be wrong. =D
__________________
* tweet *

Private Message inbox is full, email "opserty" followed by an at and a "gmail" and a dot and a "com" to contact me. =]


Sanesh. says (22:54): We need to think up a PHPWomen chatup line
Kalle Almighty says (22:54): lol
Sanesh. says (22:55): how about "I tried to use the imagecreatefromyou() function on you, but the Parser returned a T_TOO_SEXY error" ?


Reply With Quote
#3  
Old June 1st, 2009, 10:04 PM
Ross Ross is offline
/dev/null
 
Join Date: Mar 2006
From: England
iTrader: (1)
Posts: 6,026
Ross has a reputation beyond repute Ross has a reputation beyond repute Ross has a reputation beyond repute
Send a message via MSN to Ross
Re: Using MySQLi and prepared statements in PHP

Quote: Originally Posted by Sanesh. View Post
Uh! How did Kalle let you on Dev team with such yucky formatted code?!

Lol, other than that the only problem I noticed was...
PHP Code
			
$stmt $conn->prepare($query); 

Did you mean to write $mysqli instead of $conn? Because I didn't think mysql_connect() returned an object... its been about a year since I touched PHP though so I might be wrong. =D
Yeah, $conn would be the same as the $mysqli in the first example, but I've changed that now. basically (too lazy to copy and paste) the first example happens before the third one (the mysqli with the prepared statement).

For mysql mysql_connect returns a resource which you can use in your queries (it's only of use if you've got two db conns going on though). Mysqli returns an object of the MySQLi class which you use to create queries and statements which gets over the risk you had with mysql.
__________________
Quote: Originally Posted by Andy View Post
Tea + Vodka = Ross' tea

Ross = Hardcore
Reply With Quote
#4  
Old September 26th, 2009, 12:10 AM
AkumaShio's Avatar
AkumaShio AkumaShio is offline
Newbie
 
Join Date: May 2009
From: F i m *do *M u n d o
iTrader: (0)
Posts: 1
AkumaShio has a brilliant future
Send a message via MSN to AkumaShio Send a message via Skype™ to AkumaShio
Re: Using MySQLi and prepared statements in PHP

Good!!
Era so que estava faltando aqui.. :D
__________________

Reply With Quote
#5  
Old October 2nd, 2009, 01:32 AM
510carlos 510carlos is offline
Coder?
 
Join Date: Sep 2007
From: Hayward, California
iTrader: (0)
Posts: 91
510carlos is an unknown quantity at this point
Send a message via AIM to 510carlos
Re: Using MySQLi and prepared statements in PHP

Nice tut!
This helped a lot!
Reply With Quote
#6  
Old March 18th, 2010, 07:23 AM
Omari123 Omari123 is offline
Newbie
 
Join Date: Mar 2010
iTrader: (0)
Posts: 1
Omari123 has a brilliant future
Re: Using MySQLi and prepared statements in PHP

I am also thinking to develop a forum like this one, really impressive work
__________________
Shawn
Reply With Quote
#7  
Old August 4th, 2010, 11:29 PM
CriarSites CriarSites is offline
Como Criar Um Site
 
Join Date: Jun 2010
iTrader: (0)
Posts: 1
CriarSites has a brilliant future
Re: Using MySQLi and prepared statements in PHP

This also works with the latest PHP version?
Reply With Quote
Reply

Tags
database , mysql , mysqli , php , php5

Warning
You are about to reply to a thread, where the last post is over 2 weeks old. Replying without a constructive post related to the topic, will result in infractions being given out

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off



All times are GMT +1. The time now is 03:27 PM.
Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.