Populating Drop Down Menus with Select Statement

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
sergei
Forum Commoner
Posts: 33
Joined: Mon Oct 06, 2003 4:17 am

Populating Drop Down Menus with Select Statement

Post by sergei »

Can someone tell me how to populate a drop down menu using a select statement.

Thanks
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You need to get all the records out using the SELECT statement, and then you just loop through the result putting them into <option> tags to make the select box.

Mac
User avatar
sergei
Forum Commoner
Posts: 33
Joined: Mon Oct 06, 2003 4:17 am

Post by sergei »

I have this piece of code:

Code: Select all

<?

		$selectstatement = "SELECT Category_ID, Category_Type FROM category";
		$selectresult = mysql_query($selectstatement, $connection);			
		print "This works";
		while ($row = mysql_fetch_array($selectresult)) { 
			$Category_Type = $row['Category_Type'];			
			$id = $row['Category_ID'];
			if ($id == 1) {
				print("<option SELECTED value="$id">$Category_Type</option>\n"); 
			} else {
				print("<option value="$id">$Category_Type</option>\n"); 
			}
		} 
?>
When I test, it gives me the following errors:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in C:\Apache2\htdocs\metering\core.php on line 14
This works
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Apache2\htdocs\metering\core.php on line 16

Can anyone find the problem ? There is data in the database.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Where does $connection come from? Also it's a good idea to add error handling to mysql_query() calls:

Code: Select all

$selectresult = mysql_query($selectstatement, $connection) or die(mysql_error().'<p>'.$selectstatement.'</p>');
Mac
User avatar
sergei
Forum Commoner
Posts: 33
Joined: Mon Oct 06, 2003 4:17 am

Post by sergei »

Code: Select all

<?

$connection = mysql_connect($DBHOST,$DBUSER) 
		or die("Connection unsuccessful: " . mysql_error()); 						
	mysql_select_db($DBASE) 
		or die("Connection to database unsuccessful: " . mysql_error()); 


?>
I've used the $connection variable successfully in the past. No changes have been made to it.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Did you add the or die() error handling to the mysql_query() call? If so did it do anything?

Mac
Post Reply