What is the purpose of using prepared statements in PHP when fetching data from a database?

Prepared statements in PHP help prevent SQL injection attacks by separating SQL logic from user input. By using placeholders for user input, the database engine can distinguish between SQL code and data, reducing the risk of malicious SQL injection. This approach also improves performance by allowing the database to compile the SQL query once and execute it multiple times with different parameters.

// Using prepared statements to fetch data from a database in PHP

// Establish a database connection
$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
$username = 'john_doe';
$stmt->bindParam(':username', $username);

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

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

// Loop through the results and do something with them
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}