Adola
Adola

Reputation: 588

PHP mysqli slow loading.

Evening all!

I'm optimizing my website, and I'm running into some peculiar behaviour. Before, I assumed it was because of the calculations being done on the data I was using, but I'm starting to question this.

I find that running some code like:

for ($i=0; $i < 55 ; $i++) { 
  $query = "SELECT id FROM gamedata_concepts WHERE game_id=12277";

  if ($result = $mysqli->query($query){
  }
}

Takes about 3 seconds, however, if I call that query once in say, phpMyAdmin, it says it takes '.0121' seconds, multiply that by 55 (the testing number used above in the loop), and it SHOULD take appx. .6655 seconds. I'm curious as to maybe where this backend is? Or better, how I can engineer this better to be more efficient.

Thanks.

Upvotes: 2

Views: 1820

Answers (2)

David Untama
David Untama

Reputation: 592

you can use transactions to do this with more speed

$mysqli->query("START TRANSACTION");
for ($i=0; $i < 55 ; $i++) { 
  $query = "SELECT id FROM gamedata_concepts WHERE game_id=12277";

  if ($result = $mysqli->query($query){
  }
}
$mysqli->query("COMMIT");

Upvotes: 1

Mike B
Mike B

Reputation: 32155

Why not refactor your query to use IN instead of 55 queries?

SELECT id FROM gamedata_concepts WHERE game_id IN (12277, 12278, 12279, ...)

Any time you see a query being executed in a loop it's usually a bad sign.

Upvotes: 4

Related Questions