What are the best practices for handling database connections and queries in PHP to prevent errors like missing data or incorrect results?

To prevent errors like missing data or incorrect results when handling database connections and queries in PHP, it is important to properly handle exceptions, sanitize user input to prevent SQL injection attacks, and validate data before executing queries. Additionally, using prepared statements can help prevent SQL injection and ensure data integrity.

// Establish a database connection
try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Sanitize user input
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Prepare and execute a query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $user_input, PDO::PARAM_STR);
$stmt->execute();

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

// Display results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}