Home » Use PHP PDOStatement bindValue

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

Requirements:

  • PHP
  • PHP Data Objects
  • PDO Drivers
  • PDOStatement::bindValue

How to bind a parameter to a variable using PDOStatement bindValue().

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 bindValue() in PHP.

Consider below as the employees TABLE inside a MySQL DATABASE.

Select the employee record where $firstName is equal to Peter Rick using the question mark (?) placeholder.

$firstName = 'Peter Rick';
$sth = $dbh->prepare(
    "SELECT * FROM employees WHERE first_name = ?"
);
$sth->bindValue(1, $firstName, PDO::PARAM_STR);
$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 record where $lastName is equal to Thomas using the named (:name) placeholder.

$lastName = 'Thomas';
$sth = $dbh->prepare(
    "SELECT * FROM employees WHERE last_name = :lastName"
);
$sth->bindParam(":lastName", $lastName, PDO::PARAM_STR);
$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.

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *