Bind a parameter to a variable using bindValue() in PDO

January 25, 2014 | Last tested: May 2015 | 670 views | Comments

Use the PDO function bindValue() to bind a parameter to a specified variable name in PHP.

For example.

Reference: TABLE name is "members".

Please mouse over here to view the image.

Select the record with the 'firstName' value equals to Andrew using the question mark (?) placeholder.

$dbh = new PDO('mysql:host=HOST;dbname=DB_NAME','DB_USER','DB_PASSWORD'); //setup PDO connection here

$firstName = 'Andrew';
$sth = $dbh->prepare("SELECT * FROM members WHERE firstName = ?");
$sth->bindValue(1,$firstName,PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetch();

if($result){
	echo '<pre>';
		print_r($result);
	echo '</pre>';
}
else{
	echo 'record not found...';
}

Result:

Array
(
    [id] => 2
    [0] => 2
    [firstName] => Andrew
    [1] => Andrew
    [lastName] => Kimball
    [2] => Kimball
    [age] => 25
    [3] => 25
    [sex] => M
    [4] => M
    [location] => Texas
    [5] => Texas
)

 

Select the record that has a location value equals to California using the named (:name) placeholder.

$dbh = new PDO('mysql:host=HOST;dbname=DB_NAME','DB_USER','DB_PASSWORD'); //setup PDO connection here

$location = 'California';
$sth = $dbh->prepare("SELECT * FROM members WHERE location = :location");
$sth->bindValue(":location",$location,PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetch();

if($result){
	echo '<pre>';
		print_r($result);
	echo '</pre>';
}
else{
	echo 'record not found...';
}

Result:

Array
(
    [id] => 7
    [0] => 7
    [firstName] => Howard
    [1] => Howard
    [lastName] => Franklin
    [2] => Franklin
    [age] => 24
    [3] => 24
    [sex] => M
    [4] => M
    [location] => California
    [5] => California
)

 

Select a non-existent record.

$dbh = new PDO('mysql:host=HOST;dbname=DB_NAME','DB_USER','DB_PASSWORD'); //setup PDO connection here

$location = 'New York';
$sth = $dbh->prepare("SELECT * FROM lab_members WHERE location = :location");
$sth->bindValue(":location",$location,PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch();

if($result){
	echo '<pre>';
		print_r($result);
	echo '</pre>';
}
else{
	echo 'record not found...';
}

Result:

record not found...