Jump to content

another looping issue


fife

Recommended Posts

I have a select field in my join form which allows users to select one of my speicifed counties.  In the table the county is link to a country.  I am trying to echo in a select statement a loop of all the available counties in england.

here is the code

             <?php
        $qGetCounty = "SELECT * FROM Counties";
	$rGetCounty = mysql_query($qGetCounty);
	       
        echo "
        <select name=\"County\">
<optgroup label=\"England\">
	 ";
	 while ($county = mysql_fetch_assoc($rGetCounty)){
	 if($county['country']=='England') { 
	 echo "  
          <option value= '{$county['county']}'>{$county['county']}</option>
	 ";
	  }}
	  
	          echo "
         <optgroup label=\"Wales\">
	 ";
	 while ($county=='Wales'){
	 echo "  
          <option value= '{$county['county']}'>{$county['county']}</option>
	 ";
	 }
	  
	  
	            echo "
         <optgroup label=\"Scotland\">
	 ";
	 while ($county=='Scotland'){
	 echo "  
          <option value= '{$county['county']}'>{$county['county']}</option>
	 ";
	 }

echo "
        </select>
      "  ;
        ?>

 

It is not erroring but also it is not worlking correctly.  It shows all the counties in England and both the labels for scotland and wales but does not show any counties in these two areas.  I am new to loops so do not know how to fix this.  I have tried changing the line

 

while ($county=='Wales')

 

to

 

while ($county = mysql_fetch_assoc($rGetCounty))

 

But this makes no difference

Link to comment
https://forums.phpfreaks.com/topic/228084-another-looping-issue/
Share on other sites

Hi

 

You need something like this

 

<?php
$qGetCounty = "SELECT * FROM Counties ORDER BY FIELD(country,'England','Wales','Scotland'), county ";
$rGetCounty = mysql_query($qGetCounty);

echo "<select name=\"County\">";
$PrevCountry = "";
while ($county = mysql_fetch_assoc($rGetCounty))
{
	if ($county['country'] != $PrevCountry)
	{
		$PrevCountry = $county['country'];
		echo "<optgroup label='$PrevCountry'>";
	}
	echo " <option value= '{$county['county']}'>{$county['county']}</option>";
}
echo "</select>" ;
?>

 

Get the data from the table in country order, then loop through it. If the country name changes the put the country out.

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.