What are some best practices for handling database connections in PHP scripts to avoid errors like "main(): Property access is not allowed yet"?

The error "main(): Property access is not allowed yet" often occurs when trying to access properties of an object before it has been initialized. To avoid this error, make sure to properly establish a database connection before attempting to access any properties or methods of the connection object.

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

// Now you can safely access properties and methods of the $conn object
$stmt = $conn->prepare("SELECT * FROM table");
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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