What best practices should be followed to ensure SQL injection prevention when writing PHP code for database queries?

SQL injection can be prevented in PHP code by using prepared statements and parameterized queries instead of directly concatenating user input into SQL queries. This ensures that user input is treated as data rather than executable SQL code, protecting against malicious injection attacks.

// Example of using prepared statements to prevent SQL injection in PHP

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Prepare a SQL query 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(PDO::FETCH_ASSOC);

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