What are the advantages of using prepared statements in PHP PDO for database queries, and how can they prevent SQL injection vulnerabilities?
Using prepared statements in PHP PDO for database queries helps prevent SQL injection vulnerabilities by separating SQL logic from user input. This means that input values are treated as parameters and not as part of the SQL query itself, making it impossible for an attacker to inject malicious SQL code. Prepared statements also improve performance by allowing the database to optimize query execution.
// Connect to the database
$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', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Use the results as needed
foreach ($results as $row) {
echo $row['username'] . '<br>';
}