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

When writing SQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance by reducing the need for repeated query parsing. Prepared statements separate SQL logic from data input, making it safer and more efficient to execute queries. Additionally, using parameter binding can help optimize query execution by allowing the database to reuse query plans.

// Example of using prepared statements in PHP to prevent SQL injection and improve performance

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

// Prepare a SQL statement with placeholders
$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);