Avoid running SQL queries inside a loop


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);


$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);
This best practice should only be applied if it is coherent with your project's specifications.
Under CC-By-NX-SA license