What are the potential pitfalls of using a separate database connection for each data query in PHP?

Potential pitfalls of using a separate database connection for each data query in PHP include increased resource usage and decreased performance due to the overhead of establishing multiple connections. To solve this issue, it is recommended to use a single database connection throughout the script execution to minimize resource usage and improve performance.

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

// Use the $conn object for all database queries
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Process the query result
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the database connection at the end of the script
$conn->close();