tags:

views:

52

answers:

4

I recently ran across some code which the person did the first one. Would like some thoughts on if the top one is better or why a person would write it that way? Any positive reasons over the bottom way.

$result = mysql_query($query)or die("Obtaining location data failed!");
for ($i = mysql_num_rows($result) - 1; $i >=0; $i--)
{
  if (!mysql_data_seek($result, $i))
  {
    echo "Cannot seek to row $i\n";
    continue;
  }
  if(!($row = mysql_fetch_object($result)))
    continue;
  echo $row->locationname;
}
mysql_free_result($result);

vs

$result = mysql_query($query) or die("Obtaining location data failed!");
while($row = mysql_fetch_object($result)){
  echo $row->locationname;
  unset($row);
}
mysql_free_result($result);
+1  A: 

It looks like the top code is iterating through the mysql result backwards, where the first one is going through it forwards.

The second code example looks cleaner, and there is probably a way to adjust the query to get the results in reverse order in the first place, instead of the somewhat convoluted way the top loop was performed.

GSto
+1  A: 

Those two are not equivalent since only the first processes the result set in reverse order.
I'd do that with an ORDER BY x DESC clause if only to keep the code simple. When using mysql_query() the complete result set is transferred from the MySQL server to the php process before the function returns and mysql_data_seek() is only moving some pointer within the process' memory, so performace-wise it shouldn't matter much. But if you at some point decide to use an unbuffered query instead it might very well affect the performance.

VolkerK
A: 

Definitely the second one :

less code = less code to maintain =~ maybe less bugs !!

Arno
A: 

The top one has definite advantages when it comes to job security and 'lines of code' performance metrics. Apart from that there is no good reason to do what they did.

Meep3D
no, they did it to loop through the result backwards. The two sets of code are not equivalent.
GSto
If only SQL had some sort of way to order search results...
Meep3D