What best practices should be followed when executing SQL queries in PHP?

When executing SQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate SQL code from user input, making it impossible for malicious input to alter the query structure. Additionally, it is good practice to validate and sanitize user input before using it in a query to prevent unexpected behavior.

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

// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the sanitized user input to the placeholder
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

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

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