What are some best practices for constructing SQL queries in PHP?

When constructing SQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate SQL logic from user input, allowing parameters to be bound separately. This helps to sanitize inputs and prevent malicious code from being executed.

// Example of constructing SQL query using prepared statements in PHP
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();

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