Page 1 of 1

Best way to filter mySQL data *after* querying?

Posted: Wed Apr 06, 2011 5:58 pm
by BrandonR
I have a mySQL query that grabs a bunch of data, but when I display it in tables, I want to have one group of data displayed in one table and another group of data displayed in another table (based on a column, say "filtering_category"). Currently, I accomplish this this way:

Code: Select all

while($results = mysql_fetch_array($result_set) and $results['filtering_category'] == 1){
  // print table 1
}

while($results = mysql_fetch_array($result_set)){
  // print table 2
}
This seemed to work until I realized today that it cuts off the first result of the second table. I could just ask to fix the code, but I really want to know if there's a better way of accomplishing this (filtering data from a single query to display them differently).

Thanks in advance!

Re: Best way to filter mySQL data *after* querying?

Posted: Wed Apr 06, 2011 7:44 pm
by gooney0
I prefer to fetch results and save the data into an array. I then use the array latter to output.

Code: Select all

// Save results into an array
$people = mysql_fetch_array($result_set);

// now output

foreach($people as $person)
     {
     if($person['filtering_category''] == 1 )
          {
          print $person["First_Name"];
          print $person["Last_Name"];
          }
     }
I can use $people as often as I like. I can also change things if needed. Rinse and repeat.

It is also wise to get data as soon as possible in your script, and output it as late as possible. This leaves room for future changes and features.