In what situations should prepared statements be used instead of directly inserting user input into SQL queries in PHP?
Prepared statements should be used instead of directly inserting user input into SQL queries in PHP to prevent SQL injection attacks. Prepared statements separate the SQL query from the user input, which allows the database to distinguish between code and data, effectively preventing malicious SQL code from being executed.
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();