How can PDO and prepared statements be utilized in PHP to enhance the security of database queries?
Using PDO and prepared statements in PHP can enhance the security of database queries by preventing SQL injection attacks. Prepared statements separate the SQL query from the user input, which allows the database to distinguish between code and data. This helps to prevent malicious input from being executed as SQL code.
// Establish a connection to the database using PDO
$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();