What best practices should be followed when creating and executing SQL queries in PHP, especially when dealing with user input?

When creating and executing SQL queries in PHP, especially when dealing with user input, it is crucial to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements with placeholders for user input values, which are then bound to the query before execution. By doing so, you can ensure that user input is properly sanitized and secure against malicious SQL injection attempts.

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

// Prepare a parameterized SQL query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the query
$stmt->bindParam(':username', $_POST['username']);

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

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

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