Displaying mysql results in drop down list

Cant seem to display any data in a drop down list below is my code



<?php
	
	$queryData = mysql_query("SELECT SID, StateName FROM State");
	$result = mysql_fetch_array(mysql_query($queryData));   //$result now has database tables
	
	echo '<select name="State" id="State">';
	
	while($row = mysql_fetch_assoc($result))
{

    echo '<option values=' . $row["SID"] . '>' . $row["StateName"] . '</option>';

}
	echo '</select>';
	
	
	?>


That doesn’t seem quite right to me, I’d think you would want something like:


<?php
    $queryData = mysql_query("SELECT SID, StateName FROM State");
    echo '<select name="State" id="State">';
    while($row = mysql_fetch_assoc($queryData))
      {
        echo '<option values=' . $row["SID"] . '>' . $row["StateName"] . '</option>';
        }
    echo '</select>';
     ?>

But if you’re starting out, you really should ditch myqsl calls and use mysqli or PDO instead. Above code assumes you’ve connected to the database somewhere, and obviously you’d want to check if the query returns something before continuing.

Thanks

Now I have a second drop down list on the same form but the second one is not getting the data as the first on is getting.


<?Php
	$queryState = mysql_query("SELECT SID, StateName FROM State");
    echo "<select name='State' id='State' >";
	echo "<option>Select State</option>";  
    while($row = mysql_fetch_array($queryState))  
	{
		
			echo  '<option value=' . $row["SID"] . '>' . $row["StateName"] . '</option>';
		
	}
    echo '</select>';
?>
					
                    </td>
                    <td>City</td>
                    <td width="60px">
                    
    					<?php
						
$queryCity="SELECT CityName, CID FROM City";
echo '<select name="City" id="City">'; 
echo "<option>Select City</option>"; 
    while($rs = mysql_fetch_array($queryCity))  
    {
		  
        echo '<option values=' . $rs["SID"] . '>' . $rs["CityName"] . '</option>';  
    }  
	echo '</select>';
//////////////////  This will end the second drop down list ///////////

						
						?>


What is the difference between mysql_fetch_array and mysql_fetch_assoc?

mysql_fetch_assoc returns results with an associative array (not numerical) while mysql_fetch_array returns both numerical and associative (but has options to choose one or the other too).

You ought to read this: http://www.php.net/manual/en/mysqlinfo.api.choosing.php and move away from procedural mysql_ calls ASAP. mysqli may be the easiest to move over to as it still allows procedural code or of course PDO for OOP-based.

I have solved the problem.

I should have done this:


$queryCity = mysql_query("SELECT CityName, CID FROM City");

Hi gmboat,

just for an advice,you should not practice native mysql because it is deprecated,you should use PDO,…but if your project using native then you have no choice to continue it…but if you have chance to reverse the code to PDO it’s good. :slight_smile: