Skip to main content
Inspiring
February 29, 2012
Answered

How do I Loop through a recordset using PHP

  • February 29, 2012
  • 2 replies
  • 2916 views

I have a recordset containing a MySql table with 5 columns, each one containing an email address of an official in a club.

Each row represents a different club, and each column a different type of official.

The first column represents chairmen, the next treasurers etc...

The recordset is called $mailset.

I need to loop through each row of $mailset and extract the email addresses of each column and concatenate them into a string seperated by semi colons ; so it ends up like this:

peter@sos.com;paul@thatsok.com;mary@girlguides.com; and so on.

This is how the recordset is set up:

mysql_select_db($database_dummyread, $dummyread);

$query_mailset = "SELECT club_chair_email, club_treas_email, club_sec_email, club_delegate_email, club_deputy_email FROM clubs";

$mailset = mysql_query($query_mailset, $dummyread) or die(mysql_error());

$row_mailset = mysql_fetch_assoc($mailset);

$totalRows_mailset = mysql_num_rows($mailset);

?>

I tried using a  loop to step through the recordset, but it always shows the first record, so its not moving the pointer through the file.

The pseudo code aught to be something like this:

Initialise variables and move to the first record

If there are records to process

               Read a record

                    Process all columns

            Move on to the next record

else

     if there are no records

          print an error message

else

Print the results.

Can anyone give me a hint as to how to move from row to row in a recordeset under the control of a loop.

I am using PHP and MySql. (as far as I know, it is the original - not PDO or MySqli)



This topic has been closed for replies.
Correct answer Rob Hecker2

while ($mail = mysql_fetch_assoc($mail_seyt)){

extract ($mail);

echo "$club_chair_email - $club_treas_email<br/>";

}

That should put you on the right path.

2 replies

Rob Hecker2
Rob Hecker2Correct answer
Legend
February 29, 2012

while ($mail = mysql_fetch_assoc($mail_seyt)){

extract ($mail);

echo "$club_chair_email - $club_treas_email<br/>";

}

That should put you on the right path.

Inspiring
February 29, 2012

Magic Mr Hecker!

Thanks a lot.

Rob Hecker2
Legend
March 1, 2012

You're welcome. That's the pattern you will use pretty much every time you call data from your tables.

Participating Frequently
February 29, 2012

Each call to mysql_fetch_assoc($mailset) retrieves the value at the current location and increments the pointer in the recordset array. So use either a do or while loop and call mysql_fetch_assoc($mailset) from within the loop.

From the docs:

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.