Well, I figured it out. It took two queries. Probably a better way I'm not thinking about, but this works in case anyone needs/wants. Was hoping to do it all in the SQL statement I guess. $FieldGroups = $wpdb->get_results("SELECT DISTINCT Field_Group FROM ".table_name); foreach($FieldGroups as $FieldGroup) { $ReturnString .= '<h3>'.$FieldGroup->Field_Group.'</h3>'; $Fields = $wpdb->get_results($wpdb->prepare("SELECT * FROM ". table_name.' WHERE Field_Group=%s', $FieldGroup->Field_Group)); foreach($Fields as $i=>$Field) { $ReturnString .= /*Other code to build html*/ } } return $ReturnString; I am working on a WordPress site. Hence the $wpdb->get_results(). FYI, for those who aren't familiar. Best, Karl DeSaulniers Design Drumm http://designdrumm.com PS: Thanks teddy bear On Jul 22, 2015, at 11:19 PM, Karl DeSaulniers <karl@xxxxxxxxxxxxxxx> wrote: > Hello All, > How can I group database results in a foreach loop? > I have a field_group column that can have a value or not. > > I want to read from the database then display results and if the results have a matching field_group, I want to have them group in the html. > > This is my current SQL. I am using MySQL. > > $Sql = "SELECT * FROM ".table_name.' GROUP BY Field_ID, Field_Group'; > > From this I want to be able to wrap the groups in a div and add a h3 with the group name. > So if there are 5 entries in the BOB group, then the html would look like this. > > <input name="Field_Name1" />//empty Field_Group > <div id="BOB">//Field_Group = BOB > <input name="Field_Name2" /> > <input name="Field_Name3" /> > <input name="Field_Name4" /> > <input name="Field_Name10" /> > </div> > <input name="Field_Name5" />//empty Field_Group > <input name="Field_Name6" />//empty Field_Group > <div id="Charlie">//Field_Group = Charlie > <input name="Field_Name8" /> > <input name="Field_Name9" /> > <input name="Field_Name15" /> > </div> > > Am I setting this up right? > > TIA > > Best, > > Karl DeSaulniers > Design Drumm > http://designdrumm.com > > > -- PHP Database Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php