How should strings be handled in SQL queries in PHP to prevent SQL injection?

To prevent SQL injection when handling strings in SQL queries in PHP, it is important to use prepared statements with parameterized queries. This ensures that user input is treated as data rather than executable SQL code, reducing the risk of malicious SQL injection attacks.

// Example of using prepared statements to handle strings in SQL queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();