dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

Problem populating a dropdown box with MySQL query results (PHP/MySQL)

so as the title states, using the following code I have got it populating the dropbox with a single result from the query, that result being the latest added in the table.

here is my code:

<?php 
$query = "SELECT * FROM units_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
$aa = "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";
}
?>
<select name="t_unit"><? echo $aa; ?></select>

The odd thing is, I use this same code for another field, and it works, populating the dropdown with all the results, however in this case it only fills in the last unit code in the table and not all of which are attached to the particular user id.

I would appreciate anyones thoughts :D

thanks

Upvotes: 0

Views: 716

Answers (2)

j_freyre
j_freyre

Reputation: 4738

<?php 
$query = "SELECT * FROM units_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die (mysql_error());
$options = "";
while($row = mysql_fetch_assoc($result)){
    $options .= "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";
}
?>
<select name="t_unit"><? echo $options; ?></select>

should work. You forgot a . in your while loop

Upvotes: 0

bensiu
bensiu

Reputation: 25564

$aa .= "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";

add . before = and initiate $aa = ''; before while loop

Upvotes: 4

Related Questions