What are some best practices for handling database connections and queries in PHP scripts to ensure data integrity and security?

To ensure data integrity and security when handling database connections and queries in PHP scripts, it is important to use prepared statements to prevent SQL injection attacks, validate and sanitize user input, and properly handle errors.

// Establish a secure database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example_user";
$stmt->execute();

$result = $stmt->get_result();

// Fetch results and display them
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"] . "<br>";
}

// Close the connection
$stmt->close();
$conn->close();