title: SQL queries within a loop
body: <p>Google code suggests that you should AVOID sql queries within a loop. The reason being that the multiple round trips to the database significantly slows your scripts down. The example query they give is this.</p>
  
  <pre><code>$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);
  </code></pre>
  
  <p>My questions are...
  1. How important is it to keep your query out of a loop, and is it always avoidable?
  2. How can you implement a SELECT statement with this same logic. </p>
  
  <p>i.e. Let's say I have this query.</p>
  
  <pre><code>$index=0;
  while ($index &lt; count($id)) {
       $result[] = mysql_query("SELECT * FROM tblInfo WHERE site_id = '".$id[$index]."' ");
       $index++;
  }
  </code></pre>
  
  <p>How can this SELECT statement be executed outside of a loop? I have a large amount of SELECT statements that are far more complex than this. So if deemed necessary, I'd like to get these queries out of loops. If someone out there is concurring with google, could you please post some sample code.</p>
  
  <p>Any response will be greatly appreciated. </p>