What best practices should be followed when handling MySQL connections and queries in PHP scripts?

When handling MySQL connections and queries in PHP scripts, it is important to follow best practices to ensure security, efficiency, and maintainability. This includes using prepared statements to prevent SQL injection attacks, properly escaping input data, closing connections after use to conserve resources, and handling errors gracefully to provide meaningful feedback to users.

// Establish a MySQL 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);
}

// Example query using prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

while ($row = $result->fetch_assoc()) {
    // Process the results
}

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