What is the purpose of using PDO prepared statements in PHP?
Using PDO prepared statements in PHP helps prevent SQL injection attacks by separating the SQL query from the user input. This means that the input values are treated as parameters and are not directly inserted into the query, making it safer and more secure. Prepared statements also improve performance by allowing the database to optimize the query execution plan.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();