To prepare and execute a parameterized SQL statement with PDO in PHP, follow these steps:
$dsn = "mysql:host=localhost;dbname=mydatabase";
$username = "username";
$password = "password";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sql = "SELECT * FROM users WHERE username = :username AND age > :age";
$stmt = $pdo->prepare($sql);
$username = "johndoe";
$age = 25;
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['username'];
echo $row['age'];
}
Note: You can also use the bindValue()
method instead of bindParam()
if you don't need to pass variables by reference.