How can prepared statements and PDO be used to prevent SQL injection in PHP?
To prevent SQL injection in PHP, prepared statements and PDO can be used. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. PDO (PHP Data Objects) is a database access layer that provides a flexible and secure way to interact with databases in PHP.
// Establish a connection to the database using PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();