Best way to prevent SQL Injection in PHP


This way  is impossible for an attacker to inject malicious SQL.

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); 
$stmt->bind_param('s', $name); 
$stmt->execute(); $result = $stmt->get_result(); 
while ($row = $result->fetch_assoc()) {
     // do something with $row 
}

The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn’t intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE * FROM employees the result would simply be a search for the string “‘Sarah’; DELETE * FROM employees”, and you will not end up with an empty table.

Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Source : http://chelladuraii.wordpress.com/2012/07/14/best-way-to-prevent-sql-injection-in-php/

Advertisements
By Image Karthik Posted in Php

One comment on “Best way to prevent SQL Injection in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s