Binding Parameters to Statements
One topic we have mentioned in our discussion of the preparation of statement handles is bind values. You may also have come across the phrases placeholders , parameters , and binding . What are these things?
A bind value is a value that can be bound to a placeholder declared within an SQL statement. This is similar to creating an on-the-fly SQL statement such as:
$sth = $dbh->prepare( "
SELECT name, location
FROM megaliths
WHERE name = " . $dbh->quote( $siteName ) . "
" );but instead of interpolating the generated value into the SQL statement, you specify a placeholder and then bind the generated value to that. For example:
$sth = $dbh->prepare( "
SELECT name, location
FROM megaliths
WHERE name = ?
" );
$sth->bind_param( 1, $siteName );The bind_ param( )
method is the call that actually associates the supplied value with
the given placeholder. The underlying database will correctly parse
the placeholder and reserve a space for it, which is “filled
in” when bind_ param( ) is called. It is
important to remember that bind_ param( ) must be
called before
execute( );
otherwise, the missing value will not have been filled in and the
statement execution will fail.
It’s equally simple to specify multiple bind values within one
statement, since bind_ param( ) takes the index,
starting from 1, of the parameter to bind the given value to. For
example:
$sth = $dbh->prepare( " SELECT name, location FROM megaliths WHERE name = ? AND mapref = ? AND type LIKE ? " ...