How can prepared statements with named parameters in PDO be effectively utilized to prevent SQL injection vulnerabilities in PHP?
Using prepared statements with named parameters in PDO is an effective way to prevent SQL injection vulnerabilities in PHP. By binding parameters to placeholders in the SQL query, PDO handles escaping and quoting automatically, eliminating the risk of malicious input affecting the query execution.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with named parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter to a variable
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);