28.10.2014 Views

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Code-Level <strong>Defense</strong>s • Chapter 8 347<br />

OleDbConnection con = new OleDbConnection(ConnectionString);<br />

string Sql = "SELECT * FROM users WHERE username=? AND password=?";<br />

cmd = new OleDbComm<strong>and</strong>(Sql, con);<br />

// Add parameters to <strong>SQL</strong> query<br />

cmd.Parameters.Add("@username",<br />

// name<br />

OleDbType.VarChar,<br />

// data type<br />

16); // length<br />

cmd.Parameters.Add("@password",<br />

OleDbType.VarChar,<br />

16));<br />

cmd.Parameters.Value["@username"] = username;<br />

cmd.Parameters.Value["@password"] = password;<br />

reader = cmd.ExecuteReader();<br />

// set parameters<br />

// to supplied values<br />

Tip<br />

When using parameterized statements with ADO.NET, it is possible to specify<br />

less or more detail about the statement than I did in the preceding example.<br />

For instance, you can specify just the name <strong>and</strong> the value in the parameter<br />

constructor. In general, it is a good security practice to specify parameters as<br />

I did, including the data size <strong>and</strong> type, because this provides an additional level<br />

of coarse-grained validation over the data that is being passed to the database.<br />

Parameterized Statements in PHP<br />

PHP also has a number of frameworks that you can use to access a database. I’ll demonstrate<br />

three of the most common frameworks in this section: the mysqli package for accessing<br />

My<strong>SQL</strong> databases, the PEAR::MDB2 package (which superseded the popular PEAR::DB<br />

package), <strong>and</strong> the new PHP Data Objects (PDO) framework, all of which provide facilities<br />

for using parameterized statements.<br />

The mysqli package, available with PHP 5.x <strong>and</strong> able to access My<strong>SQL</strong> 4.1 <strong>and</strong> later<br />

databases, is one of the most commonly used database interfaces, <strong>and</strong> supports parameterized<br />

statements through the use of placeholder question marks. The following example shows a<br />

parameterized statement using the mysqli package:<br />

$con = new mysqli("localhost", "username", "password", "db");<br />

$sql = "SELECT * FROM users WHERE username=? AND password=?";<br />

$cmd = $con->prepare($sql);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!