What is the potential issue with inserting data in a loop in PHP?

When inserting data in a loop in PHP, the potential issue is that it can lead to multiple database queries being executed, which can impact performance. To solve this issue, you can gather all the data that needs to be inserted in the loop and then execute a single database query outside of the loop to insert all the data at once.

// Gather all data to be inserted in the loop
$dataToInsert = [];

for ($i = 0; $i < 10; $i++) {
    $dataToInsert[] = [
        'column1' => 'value1',
        'column2' => 'value2',
        'column3' => 'value3'
    ];
}

// Execute a single insert query outside of the loop
$query = "INSERT INTO table_name (column1, column2, column3) VALUES ";

foreach ($dataToInsert as $data) {
    $query .= "('{$data['column1']}', '{$data['column2']}', '{$data['column3']}'),";
}

$query = rtrim($query, ','); // Remove the last comma

// Execute the query
// $result = mysqli_query($connection, $query);