To bind parameters to a prepared statement using PDO in PHP, you can follow these steps:
Create a PDO connection to your database:
$host = 'localhost';
$dbname = 'database';
$username = 'username';
$password = 'password';
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
Prepare the SQL statement with placeholders for the parameters:
$stmt = $pdo->prepare('SELECT * FROM users WHERE age >= :age');
Bind the parameters to the placeholders using the bindValue()
or bindParam()
methods:
$age = 18;
$stmt->bindValue(':age', $age, PDO::PARAM_INT);
In the example above, we bind the value 18
to the :age
placeholder. The third parameter PDO::PARAM_INT
specifies the data type of the parameter. You can use PDO::PARAM_STR
for strings and other appropriate constants for different data types.
Alternatively, you can use bindParam()
to directly bind the parameter by reference:
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
This allows you to update the value of $age
later, and the value passed to the prepared statement will also be updated.
Execute the prepared statement:
$stmt->execute();
The prepared statement is now executed with the bound parameters.
Note: Binding parameters to prepared statements helps to prevent SQL injection attacks by properly escaping user input and treating it as data, rather than as part of the SQL query itself.