Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

Tags:

php

mysql

if...

$query = "SELECT col1,col2,col3 FROM table WHERE id > 100"
$result = mysql_query($query);

for this action:

while ($row = mysql_fetch_array($result)){
   ....
}

is this doing 1 loop (iterated x times)?

and for this one:

$row = mysql_fetch_array($result)
foreach($row as $r){
   ...
}

is this doing 2 loops (iterated x times)?

where x is the number of results


EDIT:

ok thanks guys, ok I basically phrased this question really, really badly.

in retrospect it should have been

'does mysql_fetch_array() only return one row each time it is called'

I an now happy that my understanding of mysql_fetch_array() was v. incorrect!

thanks for your time!

like image 377
Haroldo Avatar asked Jun 04 '10 12:06

Haroldo


2 Answers

I'm assuming mysql_fetch_array() perfroms a loop, so I'm interested in if using a while() in conjunction with it, if it saves a nested loop.

No. mysql_fetch_array just returns the next row of the result and advances the internal pointer. It doesn't loop. (Internally it may or may not use some loop somewhere, but that's irrelevant.)

while ($row = mysql_fetch_array($result)) {
   ...
}

This does the following:

  1. mysql_fetch_array retrieves and returns the next row
  2. the row is assigned to $row
  3. the expression is evaluated and if it evaluates to true, the contents of the loop are executed
  4. the procedure begins anew
$row = mysql_fetch_array($result);
foreach($row as $r) {
    ...
}

This does the following:

  1. mysql_fetch_array retrieves and returns the next row
  2. the row is assigned to $row
  3. foreach loops over the contents of the array and executes the contents of the loop as many times as there are items in the array

In both cases mysql_fetch_array does exactly the same thing. You have only as many loops as you write. Both constructs do not do the same thing though. The second will only act on one row of the result, while the first will loop over all rows.

like image 70
deceze Avatar answered Oct 13 '22 08:10

deceze


It depends how many rows are returned in $results, and how many columns there are in $row?

like image 33
TheDeadMedic Avatar answered Oct 13 '22 09:10

TheDeadMedic