What potential issues can arise when using multiple MySQL queries within a loop in PHP?

When using multiple MySQL queries within a loop in PHP, potential issues can arise due to the overhead of establishing a new database connection for each query, leading to decreased performance and increased server load. To solve this issue, it is recommended to establish a single database connection outside of the loop and reuse it for all queries within the loop.

// Establish a single database connection outside of the loop
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Loop through data and execute queries using the same connection
foreach ($data as $item) {
    $query = "INSERT INTO table_name (column1, column2) VALUES ('$item->value1', '$item->value2')";
    if (mysqli_query($connection, $query)) {
        echo "Record inserted successfully";
    } else {
        echo "Error: " . $query . "<br>" . mysqli_error($connection);
    }
}

// Close the database connection after the loop
mysqli_close($connection);