Having trouble with multiple while loops

I have created a form for my users to choose / edit categories associated with their profile.

I have a main category and then sub-categories which they choose.

The sub-categories are appearing 3 times for every main category heading. This test user has 3 chosen so it’s looping how ever many options are picked and I cannot figure out why. The code has 3 while loops which is likely causing the problem. Is there another way to do this?

Table breakdown

  1. priv_type : main category headings
  2. priv_cat : sub categories that the user picks
  3. catmaster: master table that lists the physid (userid) and the sub-cateogries they belong to
  4. physinfo: user table with all the personal info.

This is an edit form so it needs to load and display all their current selection and then allows them to edit/change which categories they belong to.


//get category types
$sql23 = "select * from priv_type order by cat_type asc";
$result23 = mysql_query($sql23);

while ($row23=mysql_fetch_array($result23))
{
echo"<strong>$row23[title]</strong><br />";	
$cat_type = $row23['cat_type'];

//Get sub category names
$sql21 = "select * from priv_cat WHERE cat_type='$row23[cat_type]' order by category asc";
$result21 = mysql_query($sql21);	
while ($row21=mysql_fetch_array($result21))
{
//Get the categories values from the category table
$sql22 = "SELECT * FROM catmaster WHERE physid=$physid";
$result22 = mysql_query($sql22, $db);

while ($row22=mysql_fetch_array($result22))
{
	if ($row22['cid'] == $row21['cid'])
	{
	echo "<input type=\\"checkbox\\" name=\\"cat[]\\" value=\\"$row21[cid]\\" checked>$row21[category]<br>";
	}
	else
	{
	echo "<input type=\\"checkbox\\" name=\\"cat[]\\" value=\\"$row21[cid]\\">$row21[category]<br>";
	}
	

}
} //end while1
} // end while for priv_type

Appreciate any advice! Thanks in advance.

You don’t want that third while loop ($row22=…) nested in any of those other loops. You can do that query first and have one array with all of those values then do your check to see if your $row21[‘cid’] is in that array. So something like this


$categories = array();
$sql22 = "SELECT * FROM catmaster WHERE physid=$physid";
$result22 = mysql_query($sql22, $db);

while ($row22=mysql_fetch_array($result22))
{
  $categories[ $row22['cid'] ] = 1;
}

Then later inside those loops


if( isset( categories[ $row21['cid'] ] ) ) {
  // checked
} else {
  // not checked
}

Thank you so much! You were exactly right, I moved that query and it worked perfectly :slight_smile: