开发者

More than one mysql_fetch_array()

CODE1:

while( $row1 = mysql_fetch_array($result2) && $row2 = mysql_fetch_array($result4) )
{
 $details[0] = $row1[0];
 $details[1] = $row2[0];
 var_dump($details[0]);
 var_dump($details[1]);
}

OUTPUT1:

NULL string(1) "5" 

CODE2:

while($row1 = mysql_fetch_array($result2))
{
 $details[0] = $row1[0];
 var_dump($details[0]);
}
while($row2 = mysql_fetch_array($result4))
{
 $details[1] = $row2[0];
 var_dump($details[1]);
}

OUTPUT2:

string(6) "728548" string(1) "5"

**OUTPUT2** is the desired result. I have checked the rest portion of my code that I haven't mentioned here, nothing is wrong with that. Using **CODE1** instead of **CODE2** gives wrong result. I tried **CODE1** just for reducing the length of my code but it isn't working. Why can't we use mo开发者_如何学JAVAre than one mysql_fetch_array() like I did in **CODE1** ?


The operator precedence of && is higher than =. So, put parenthesis around the two parts and try this:

while(($row1 = mysql_fetch_array($result2)) && ($row2 = mysql_fetch_array($result4)))


Thats like doing

$true = false;

while(true && $true)
{
   $true = false;
}

if anyone of them becmome false / null the other will fail aswell, so unless there Exactly the same amount of rows you would run into problems!

what your best of doing in a situation like that is

while( ($result_2 = mysql_fetch_array($result2)) || ($result_4 = mysql_fetch_array($result4)))
{
    if($result_2)
    {
        //Do something
    }
    if($result_4)
    {
        //Do something
    }
}

using the || / or allows the one to be cancelled out and the other to continue, but this is really not good programming standards !


mysql_fetch_array() processes DB results row by row. if you do more than mysql_fetch_array in one loop, this means you only walk N row.

where N is the minimum number of rows selected by your '$result's.


The only proper way to reduce code length is to make a function.
For example a function which will take a query and it's parameters as arguments and return an array.
Like this one

<?
function dbgetarr(){
  $a = array();
  $query = $args[0];
  unset ($args[0]);
  foreach ($args as $key => $val) {
    $args[$key] = "'".mysql_real_escape_string($val)."'";
  }
  $query = vsprintf($query, $args);

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
  } else {
    while($row = mysql_fetch_assoc($res)) $a[]=$row;
  }
  return $a;
}

but it seems you need not array nor while operator in your case.
But just as silly code as

$row1 = mysql_fetch_array($result2) 
$row2 = mysql_fetch_array($result4)
$details = array($row1[0],$row2[0]);

so we can learn from this that to understand what are you doing always helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜