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

January 18, 2014 | Last tested: June 2015 | 741 views | Comments

Bind a parameter to a specified variable name using the PDO function bindParam() in PHP.

For example.

Reference: TABLE name is "members".

Please mouse over here to view the image.

Select the record with an ID equals to 1 using the question mark (?) placeholder.

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

$id = 1;
$sth = $dbh->prepare("SELECT * FROM members WHERE id = ?");
$sth->bindParam(1,$id,PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch();

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

Result:

Array
(
    [id] => 1
    [0] => 1
    [firstName] => Barbara
    [1] => Barbara
    [lastName] => Jackson
    [2] => Jackson
    [age] => 27
    [3] => 27
    [sex] => F
    [4] => F
    [location] => Florida
    [5] => Florida
)

 

Select the record with an ID equals to 1 using the named (:name) placeholder.

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

$id = 3;
$sth = $dbh->prepare("SELECT * FROM members WHERE id = :id");
$sth->bindParam(":id",$id,PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch();

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

Result:

Array
(
    [id] => 3
    [0] => 3
    [firstName] => John
    [1] => John
    [lastName] => Baker
    [2] => Baker
    [age] => 28
    [3] => 28
    [sex] => M
    [4] => M
    [location] => Arkansas
    [5] => Arkansas
)

 

Select a non-existent record.

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

$id = 11;
$sth = $dbh->prepare("SELECT * FROM members WHERE id = ?");
$sth->bindParam(1,$id,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...