How can prepared statements in mysqli or PDO help prevent SQL injection attacks in PHP applications?

SQL injection attacks occur when malicious SQL statements are inserted into input fields of a web application, allowing attackers to manipulate the database. Prepared statements in mysqli or PDO help prevent SQL injection attacks by separating SQL code from user input. This means that input parameters are treated as data rather than executable code, making it impossible for attackers to inject malicious SQL statements.

// Using prepared statements with PDO to prevent SQL injection

// Establish a connection to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}