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

When preparing and executing SQL queries in PHP for database operations, it is important to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements with placeholders for dynamic values in the query. Additionally, always sanitize user input to prevent malicious code from being executed.

// Establish a connection to the database
$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 parameter value to the placeholder
$stmt->bindParam(':username', $username);

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

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