What are best practices for handling SQL queries in PHP to avoid errors and improve performance?

When handling SQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance by reusing query execution plans. Additionally, using parameterized queries can help sanitize user input and prevent errors in SQL syntax.

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

// Prepare a SQL statement using a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind parameters and execute the query
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

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