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

When handling database queries in PHP, it is essential to use prepared statements to prevent SQL injection attacks and improve performance by reusing query execution plans. Additionally, it is recommended to properly sanitize input data and validate user input before executing queries to avoid errors.

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind parameter values to placeholders
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

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

// Fetch results
$results = $stmt->fetchAll();