What best practices should be followed when handling database connections and queries in PHP scripts to ensure data integrity?

To ensure data integrity when handling database connections and queries in PHP scripts, it is important to follow best practices such as using prepared statements to prevent SQL injection attacks, validating user input before executing queries, and properly sanitizing data before inserting or updating records in the database.

// Establish a database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);