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

When preparing and executing SQL queries in PHP, it is important to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements with placeholders for user input data. By binding parameters to these placeholders, you can ensure that user input is properly sanitized before being executed as part of a SQL query.

// 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 parameters to placeholders
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

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