Running query two times

I have a mysql query

$sql = "SELECT contents.entity_id, contents.entity_type, contents.rack_id, contents.entity_x_pos, contents.entity_y_pos, contents.entity_width, contents.entity_height, contents.entity_title, contents.display,
		racks.title
		FROM contents 
		INNER JOIN racks ON racks.rack_id = contents.rack_id 
		WHERE contents.location = 'Watch Floor'";
		
        $result = mysqli_query($conn, $sql);

which works when expected when using

 if (mysqli_num_rows($result) > 0) {
								
					while($row = mysqli_fetch_assoc($result)) {
						
					   if($row['entity_type'] == 1 )
					   {
						   echo '<rect x="'.$row['entity_x_pos'].'" y="'.$row['entity_y_pos'].'" width="'.$row['entity_width'].'" height="'.$row['entity_height'].'" />';
						   echo "\r\n";
					   } else { 
						   echo '<a href="">';
						   echo '<rect x="'.$row['entity_x_pos'].'" y="'.$row['entity_y_pos'].'" width="'.$row['entity_width'].'" height="'.$row['entity_height'].'" />';
						   echo '</a>';
						   echo "\r\n";
					   }
					} 
					
				} 

to display the results.
Id like to display the results again, so further down the page, I have

if (mysqli_num_rows($result) > 0) {
					 
echo mysqli_num_rows($result);
					
	while($row = mysqli_fetch_assoc($result)) {
	echo 'In while';
					
	echo $row['rack_id'];
	}
					
} else {
				  
echo "<tr><td colspan='5' style='text-align:center'>0 results</td></tr>";
				 
}

when the page is run, the 2nd if statement only shows 6, so is the while statement not working, cause $result is 6

That’s because you’ve already run to the end of the array once. To reset it, you need to add this right before the second iteration

mysqli_data_seek($result, 0);
1 Like

Or you could grab all the results to an array in the first place and iterate through that, or build the display string for the second loop while you work through the first one, and then display it at the appropriate time.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.