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
heyjim
Forum Newbie
Posts: 10 Joined: Fri Aug 22, 2014 12:01 pm
Post
by heyjim » Sun Aug 24, 2014 7:24 am
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
Celauran
Moderator
Posts: 6427 Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada
Post
by Celauran » Sun Aug 24, 2014 8:21 am
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
Post
by heyjim » Sun Aug 24, 2014 12:01 pm
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 (1.63 KiB) Viewed 2253 times
Celauran
Moderator
Posts: 6427 Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada
Post
by Celauran » Sun Aug 24, 2014 12:26 pm
Just add an empty option before the while loop.