Skip to main content
1 of 3
Peter
  • 123
  • 5

Effective alternative to SQL Queries in a loop

I've read somewhere on stackoverflow that doing queries in a loop is very inefficient. It will hammer your SQL server and make your script very slow.

Sample code:

// Connect to SQL Server 1
$query = "SELECT * FROM
articles
";

$resource = mysql_query($query);
$articles = array();
while $record = mysql_fetch_assoc($resource) {
    $articles[] = $record;
}

// The part that bothers me:
// (Note: this is executed on a different sql server)
foreach ($articles as $article) {
    // Connect to SQL server 2
    $sQuery = "SELECT artcode FROM articles WHERE id='".$article['id']."'";
    $sResource = mysql_query($query);
    if (mysql_num_rows($sResource) == 1) {
        $data = mysql_fetch_assoc($sResource);
        // Connect to SQL Server 1 again ...
        // This will be executed on the first sql server again
        $uQuery = "UPDATE articles SET artcode='".$data['artcode']."' WHERE id='".$article['id']."' LIMIT 1";
        $uResource = mysql_query($query);
    }
}

How would I go and make this code more efficient. (In best case scenario avoiding doing the query in a loop.)

Peter
  • 123
  • 5