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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

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

$cmd->bind_param("ss", $username, $password); // bind parameters as strings<br />

$cmd->execute();<br />

The PEAR::MDB2 package is a widely used <strong>and</strong> vendor-independent framework for<br />

accessing databases. MDB2 supports named parameters using the colon character <strong>and</strong> using<br />

placeholder question marks. The following example demonstrates the use of MDB2 with<br />

placeholder question marks to build a parameterized statement. Note that the data <strong>and</strong> types<br />

are passed in as an array which maps to the placeholders in the query.<br />

$mdb2 =& MDB2::factory($dsn);<br />

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

$types = array('text', 'text');<br />

// set data types<br />

$cmd = $mdb2->prepare($sql, $types, MDB2_PREPARE_MANIP);<br />

$data = array($username, $password);<br />

$result = $cmd->execute($data);<br />

// parameters to be passed<br />

The PDO package, which is included with PHP 5.1 <strong>and</strong> later, is an object-oriented<br />

vendor-independent data layer for accessing databases. PDO supports both named parameters<br />

using the colon character <strong>and</strong> the use of placeholder question marks. The following example<br />

demonstrates the use of PDO with named parameters to build a parameterized statement:<br />

$sql = "SELECT * FROM users WHERE username=:username AND" +<br />

"password=:password";<br />

$stmt = $dbh->prepare($sql);<br />

// bind values <strong>and</strong> data types<br />

$stmt->bindParam(':username', $username, PDO::PARAM_STR, 12);<br />

$stmt->bindParam(':password', $password, PDO::PARAM_STR, 12);<br />

$stmt->execute();<br />

Parameterized Statements in PL/<strong>SQL</strong><br />

Oracle PL/<strong>SQL</strong> offers also the possibility of using parameterized queries in database-level<br />

code. PL/<strong>SQL</strong> supports binding parameters using the colon character with an index<br />

(e.g., :1). The following example demonstrates the use of PL/<strong>SQL</strong> with bound parameters<br />

to build a parameterized statement in an anonymous PL/<strong>SQL</strong> block:<br />

DECLARE<br />

username varchar2(32);<br />

password varchar2(32);<br />

result integer;<br />

BEGIN

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

Saved successfully!

Ooh no, something went wrong!