ecometer

Avoid running SQL queries inside a loop

(Development)
#55

SQL queries inside a loop seriously hinder performance, especially if the SQL server(s) are not on the local machine. That is because these servers are designed to handle several selections, insertions or modifications in one single query or transaction.
Wrongly used, these queries unnecessarily consume CPU power, RAM and bandwidth.

Instead of:

foreach ($userList as $user) {
    $query = 'INSERT INTO users (first_name,last_ name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; mysql_query($query);
}

write:

$userData = array();
foreach ($userList as $user) {
    $userData[] = '("' . $user['first_name'] . '",  "'. $user['last_name'] . '")';
}
$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData); mysql_query($query);