ADOdb

Database Abstraction Layer for PHP

User Tools

Site Tools


v5:userguide:learn_bind:bind_vars

This is an old revision of the document!


Using Bind Variables

Description

Using bind variables (sometimes known as parameterization) is an important way to prevent SQL Injection attacks, and should be uses as a matter of course on any internet-facing web site, in addition, there may be performance improvements in statements executed multiple times.

Bind Variables In ADOdb

Most methods that accept an SQL statement as a parameter, also accept an array of bind variables to insert into the statement.

/*
* Using a MySQL database
*
* Statement without Binding
*/
$sql = "SELECT * FROM table WHERE col1='A' AND col2='B' AND col3='C'";
$result = $db->execute($sql);
 
/*
* Same statement with binding
*/
$bindVars = array('A','B','C');
$sql = "SELECT * FROM table WHERE col1=? AND col2=? AND col3=?";
$result = $db->execute($sql,$bindVars);

Note that the number of variable in the $bindVars array must match the bind placeholders (?)

Bind Placeholders Across Databases

Bind placeholders vary from one database to another, so ADOdb provides a method param() that returns a database specific placeholder. Using the above example, we can write it as a portable statement:

$bindVars = array('A','B','C');
 
$col1Ph = $db->param('col1');
$col2Ph = $db->param('col2');
$col2Ph = $db->param('col3');
 
$sql = "SELECT * FROM table WHERE col1=$col1Ph AND col2=$col2ph AND col3=$colPh";
$result = $db->execute($sql,$bindVars);

In the above example, you can see that it is necessary to obtain a unique placeholder for each bind variable. This is because in some databases, the placeholder is uniquely associated with the database. So in the above example would appear as follows:

MySQL

SELECT * FROM table WHERE col1=? AND col2=? AND col3=?

Oracle

SELECT * FROM table WHERE col1=:col1 AND col2=:col2 AND col3=:col3

PostgreSQL

SELECT * FROM table WHERE col1=$1 AND col2=$2 AND col3=$3

Databases Without Bind Support

You can still use the bind form of execute in ADOdb if the database does not support binding. In this case ADOdb simply rewrites the query statement for you back into the non-bind form.

v5/userguide/learn_bind/bind_vars.1458692484.txt.gz · Last modified: (external edit)