How to prepare and execute a parameterized SQL statement with PDO in PHP?

To prepare and execute a parameterized SQL statement with PDO in PHP, follow these steps:

  1. Establish a PDO database connection:
$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(); }
  1. Prepare your SQL statement with placeholders for the parameters:
$sql = "SELECT * FROM users WHERE username = :username AND age > :age"; $stmt = $pdo->prepare($sql);
  1. Bind the values to the parameters:
$username = "johndoe"; $age = 25; $stmt->bindParam(':username', $username, PDO::PARAM_STR); $stmt->bindParam(':age', $age, PDO::PARAM_INT);
  1. Execute the prepared statement:
$stmt->execute();
  1. Fetch the result of the executed statement:
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.