What are the benefits of consolidating database connections in PHP scripts, and how can this practice help prevent errors like "Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given"?

When database connections are consolidated in PHP scripts, it helps in managing resources efficiently and avoids opening multiple connections simultaneously. This practice can prevent errors like "Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given" which occurs when the query fails to return a valid resource. By consolidating connections, you can ensure that the resource is properly handled and avoid such errors.

<?php
// Consolidating database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Query execution
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result === false) {
    die("Error executing query: " . $conn->error);
}

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

// Closing connection
$conn->close();
?>