How can prepared statements in PHP help prevent SQL injection attacks, and why are they important for database security?
Prepared statements in PHP help prevent SQL injection attacks by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it impossible for an attacker to inject malicious SQL commands. Prepared statements are important for database security because they provide a secure way to interact with the database and protect against potential attacks.
// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Fetching results
$results = $stmt->fetchAll();