Page 1 of 1

Dropdown list from MySQL

Posted: Sun Aug 24, 2014 7:24 am
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

Re: Dropdown list from MySQL

Posted: Sun Aug 24, 2014 8:21 am
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>

Re: Dropdown list from MySQL

Posted: Sun Aug 24, 2014 12:01 pm
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.

Re: Dropdown list from MySQL

Posted: Sun Aug 24, 2014 12:26 pm
by Celauran
Just add an empty option before the while loop.