RE: [PHP] What's faster? MySQL Queries or PHP Loops?
| From: | Jay Blanchard | Date: | Wed, 08 Sep 2004 18:36:23 +0000 |
| Subject: | RE: [PHP] What's faster? MySQL Queries or PHP Loops? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-196149@lists.php.net to get a copy of this message | ||
[snip]
I don't completely understand your terminology, but it's always faster
to get all of your data with a single query rather than a query per
loop. Of course, the difference is that it also requires more memory. In
general,
if you have the memory, use it. It will always be faster.
[/snip]
+1
However, there is a point of diminishing returns that we haven't spoken
of. Dependent upon hardware and overhead, the size of the data to be
manipulated (say 10k records vs. 100k records, in numbers or record
size) will play an important part in speed. Always most efficient is the
query once model. Don't forget that inserts and updates always take
longer (especially with indexed columns). For mid-sized (and I know that
for each of us that is defined differently) databases it's a real
balancing act.
One thing that needs to be pointed out here is that you can use PHP and
MySQL to the fullest by planning data manipulation with PHP more
efficiently. It takes more work up front to figure out all of the
details but consider the following examples....
---------------------------------------------------------
$bar = 12;
$sql = "SELECT
foo FROM table1 WHERE conditions ";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result)){
$insert = "INSERT INTO table2 (newFoo) VALUES ('" . ($bar
+
$row['foo']) . "') ";
$insertResult = mysql_query($insert, $connection);
}
---------------------------------------------------------
or you could do this ....
---------------------------------------------------------
$bar = 12;
$sqlSelectCalculateAndInsert = "INSERT INTO table2 (newFoo) ";
$sqlSelectCalculateAndInsert .= "SELECT (foo + " . $bar . ") FROM
table WHERE conditions ";
$result = mysql_query($sqlSelectCalculateAndInsert, $connection);
---------------------------------------------------------
HTH