Jump to content

help with while


atticus

Recommended Posts

I want to query the database and return the username once for each record while returning all the files associated with the cust_id.

 

I am using two while loops, but it is not working.  Any suggestions:

 

$sql = "SELECT * FROM upload2 ORDER BY cust_id";
$query = mysql_query($sql);
while($myrow = mysql_fetch_array($query)) {
echo "".$myrow['cust_id']."<br />";
while($row = mysql_fetch_array($query)) {
echo "<a href=\"view.php?id=$row[id]\">".$row['title']."</a><br />";
echo "<br />";
} }

 

I am not getting any errors, its only displaying the last record in the database.

 

 

Link to comment
Share on other sites

There are two ways to do this.  One is to have one loop using mysql_fetch_array(), and to detect when cust_id changes.  When it changes, you print out the new one and continue printing files.

 

The other way is to have one query that fetches cust_id only, and an inner loop with a second query fetching that user's files.

 

The first way should be faster, the second more memory efficient (if memory is an issue).

 

In either case, you can't do a second loop inside another loop using the same query result.  That is what is causing the problem.

Link to comment
Share on other sites

in addition....

 

you have two loop but the first loop will only run once and the next loop finish or extract all the data in your query

 

 

while($myrow = mysql_fetch_array($query)) <-- this will only loop once

 

while($row = mysql_fetch_array($query)) <-- loop till it gets all the contents in your query

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.