What are the advantages of using prepared statements and parameterized queries instead of directly embedding user input in SQL queries in PHP code?

Using prepared statements and parameterized queries in PHP code helps prevent SQL injection attacks by separating SQL logic from user input. This approach allows the database to distinguish between code and data, making it more secure and efficient. By using placeholders for user input, the database can safely handle special characters and prevent malicious code execution.

// Using prepared statements and parameterized queries to prevent SQL injection

// 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
$stmt->bindParam(':username', $_POST['username']);

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

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

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