Avoid doing SQL queries within a loop

A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

$userList = array(
array('first_name'=>"Biren",'last_name'=>"Shah"),
array('first_name'=>"Majolee",'last_name'=>"InfoTech")
);

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

Produces:

INSERT INTO users (first_name,last_name) VALUES("Biren", "Shah");
INSERT INTO users (first_name,last_name) VALUES("Majolee", "InfoTech")

Instead of using a loop, you can combine the data into a single database 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);

Produces:

INSERT INTO users (first_name,last_name) VALUES("Biren", "Shah"),("Majolee", "InfoTech")

Read previous post:
Error suppression with @ is very slow

In PHP, @ is called the error suppression operator. It is sometime a convenient way to tell PHP that it...

Close