Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple PHP WHILE loops using the same query

Tags:

loops

php

mysql

$query1 = "SELECT * FROM idevaff_affiliates";
$affiliateID = mysql_query($query1) or die(mysql_error());

This is my query above - I would like to use it for two WHILE loops

The first one is in the header section - setting up jquery

while($row = mysql_fetch_assoc($affiliateID)){
}

The second is used in a while loop in the body

while($row = mysql_fetch_assoc($affiliateID)){
}

Why can't I get it to work? - I did get it working but had to make two queries using the same SELECT info using two different variables.

like image 951
Kauthon Avatar asked Aug 28 '09 23:08

Kauthon


1 Answers

Calling mysql_fetch_assoc() retrieves the next row (i.e., the next one you haven't already retrieved). Once you've retrieved all the rows, it returns false. So, once you've gotten through that first loop, you have retrieved all the rows, and all you'll get back is false every time!

If you need to reuse the same data twice, how about putting it all in an array?

$rows = array();
while($row = mysql_fetch_assoc($affiliateID)){ 
    $rows[] = $row;
}

Now you can iterate through $rows as many times as you like:

foreach($rows as $row) { ... }
like image 136
VoteyDisciple Avatar answered Nov 09 '22 06:11

VoteyDisciple