Dropdown list from MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
heyjim
Forum Newbie
Posts: 10
Joined: Fri Aug 22, 2014 12:01 pm

Dropdown list from MySQL

Post by heyjim »

Hi all,

I'm running a SQL statement to collect some data and display, which works fine on it's own.

However, I can't work out how to get that data into a dropdown menu. Here is my current code:

Code: Select all

<?php

include("php/includes/error_check.php");
include("php/includes/db_config.php");
include("php/includes/check_sql.php");

//SQL statement
$result = mysqli_query($con,"SELECT * FROM tbl_customers");

	while($companyname = mysqli_fetch_array($result))
		echo "<option value=$companyname[companyname]>$companyname[companyname]</option>";
		 	
?>

<select name="dropdown">
		<?php  echo $result; ?>
</select>
I'm obviously missing something or going about it the wrong way when it comes to the <select></select> section but I can't work out what.

Thanks
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Dropdown list from MySQL

Post by Celauran »

Iterate over the result set inside your select tags, or save the results to a variable and echo that.

Code: Select all

<?php

include("php/includes/error_check.php");
include("php/includes/db_config.php");
include("php/includes/check_sql.php");

//SQL statement
$result = mysqli_query($con,"SELECT * FROM tbl_customers");

?>

<select name="dropdown">
<?php while ($companyname = mysqli_fetch_array($result)): ?>
	<option value="<?= $companyname['companyname']; ?>"><?= $companyname['companyname']; ?></option>
<?php endwhile; ?>
</select>
heyjim
Forum Newbie
Posts: 10
Joined: Fri Aug 22, 2014 12:01 pm

Re: Dropdown list from MySQL

Post by heyjim »

Celauran wrote:Iterate over the result set inside your select tags, or save the results to a variable and echo that.

Code: Select all

<?php

include("php/includes/error_check.php");
include("php/includes/db_config.php");
include("php/includes/check_sql.php");

//SQL statement
$result = mysqli_query($con,"SELECT * FROM tbl_customers");

?>

<select name="dropdown">
<?php while ($companyname = mysqli_fetch_array($result)): ?>
	<option value="<?= $companyname['companyname']; ?>"><?= $companyname['companyname']; ?></option>
<?php endwhile; ?>
</select>
Brilliant!

Is there a way of making the default value empty? Currently, the first value is the first in the database.
Attachments
dropdown.png
dropdown.png (1.63 KiB) Viewed 2254 times
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Dropdown list from MySQL

Post by Celauran »

Just add an empty option before the while loop.
Post Reply