How can the use of prepared statements in PHP prevent security risks when interacting with a database?

Using prepared statements in PHP can prevent security risks when interacting with a database by separating SQL logic from user input. This helps to prevent SQL injection attacks, where malicious SQL queries are injected into input fields. Prepared statements parameterize the SQL query, meaning that user input is treated as data rather than executable code.

// Using prepared statements to prevent SQL injection

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', '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();