How can the use of prepared statements in PHP prevent SQL injection vulnerabilities?
Using prepared statements in PHP prevents SQL injection vulnerabilities by separating SQL code from user input. This means that user input is treated as data rather than executable SQL code, making it impossible for an attacker to inject malicious SQL queries. Prepared statements also automatically escape special characters in user input, further protecting against SQL injection attacks.
// 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 user input to the prepared statement
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();