Bind a parameter to a specified variable name using the PDO function PDOStatement bindParam()
in PHP. Prepare the statement using a named (:name)
or question mark (?)
placeholder in the SQL statement.
Requirements:
- PHP
- PHP Data Objects
- PDO Drivers
- PDOStatement::bindParam
How to bind a parameter to a variable using PDOStatement bindParam()
.
Make sure the connection to MySQL Database have already been successfully made. And assign the connection object to variable $dbh
.
The objective is to Bind a parameter to a specified variable name using the PDO function PDOStatement bindParam()
in PHP.
Consider below as the employees TABLE inside a MySQL DATABASE.
Select the employee record where $id is equal to 2 using the question mark (?)
placeholder.
$id = 2;
$sth = $dbh->prepare("SELECT * FROM employees WHERE id = ?");
$sth->bindParam(1, $id, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch();
echo '<pre>';
print_r($result);
echo '</pre>';
Result.
Array
(
[id] => 2
[0] => 2
[first_name] => Peter-Rick
[1] => Peter-Rick
[last_name] => Williams
[2] => Williams
)
Select the employee data where $id is equal to 3 using the named (:name)
placeholder.
$id = 3;
$sth = $dbh->prepare("SELECT * FROM employees WHERE id = :id");
$sth->bindParam(":id", $id, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch();
echo '<pre>';
print_r($result);
echo '</pre>';
Result:
Array
(
[id] => 3
[0] => 3
[first_name] => Mary-Ann
[1] => Mary-Ann
[last_name] => Thomas
[2] => Thomas
)
Notes:
- Always sanitize user inputs.
- The variable is bound as a reference and will only be evaluated at the time that
PDOStatement::execute()
is called.
Leave a Reply