Question

I tried to use mysqli_fetch_array twice in a code, and it seems not to work.

<?php 
$i=1; 
while ($i < $x)
{     
while($data=mysqli_fetch_array($result))   
  {     
   echo $i;
   echo $data['ID'];   
  }    
}    

while {$i > $x)
{     
 while($data=mysqli_fetch_array($result))   
 {     
  echo $i; 
  echo $data['ID2']    
 }    
}    
?>

This doesn't work for the second case. Why? Is there any way to get my idea to work? I want to use some of the array values in one place, and some in another

Was it helpful?

Solution

After you fetch all rows the pointer is at the end of the result set and you cannot fetch more. You need to reset it to the first row before attempting to fetch from it again:

mysqli_data_seek($result, 0);

Alternately, the first time through assign rows to an array and use that later:

while($data=mysqli_fetch_array($result)) {     
   $rows[] = $data;   
}    

foreach($rows as $row) {
    //whatever
}

Depending on what you are doing not a great way to split up rows, but based on your comments (you have to increment your counter):

$i=1; 
while($data=mysqli_fetch_array($result) && $i < 11) {     
   echo $data['ID'];   
   $i++;
}    

while($data=mysqli_fetch_array($result) && $i < 21) {     
   echo $data['ID2'];
   $i++;    
}    

OTHER TIPS

Where are you resetting the vars, also you should do the while loop like this:

while ( ($i < $x) || ($data=mysqli_fetch_array($result) ) )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top