What best practices should be followed when constructing SQL queries in PHP to avoid errors and improve performance?

When constructing SQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Prepared statements separate the SQL query from the user input, reducing the risk of malicious code execution. Additionally, using placeholders instead of directly inserting user input into the query helps to maintain code readability and reusability.

// Example of using prepared statements in PHP to construct SQL queries
$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();

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

foreach ($result as $row) {
    // Process the query results
}