Forum Moderators: coopster

Message Too Old, No Replies

Adding values from MySQL database to drop menu and using selection

         

eawade

2:47 pm on Feb 24, 2009 (gmt 0)

10+ Year Member



I allow a member to create new styles for a program. They can save each style to a table called style_custom. A person can have more than one style in that table and the name of each can be found in the column called name. All I want to do is retrieve all of the styles that a member has from the style_custom table and put them in a drop memu. I'm using the belowe code and it is only listing one style from the table. NOTE: the member that I am querying has ten styles, but only one is showing up in the drop menu. When a member selects an item from the drop member the program will perform a given function when submit button is pressed. This is seemingly simple but I'm having a difficult time getting it to work.

<?php

//DB connection code here....

//$member stores the member name obtained from the seesion variable. This is created when
//member logs in.... This part works fine with the rest of the program.

//Run query
$q = "SELECT name FROM style_custom WHERE member = '$member'";
$r = mysqli_query($dbc, $q);

while ($row = mysqli_fetch_array($r)) {
$val = $row["name"];
}

?>
<html>

<head>
</head>
<body>
<form>
<select name="grab">
<br /><option value="<?php echo $val ?>"><?php echo $val ?><br/></option>
</select>
</form>

</body>

</html>

blang

3:42 am on Feb 25, 2009 (gmt 0)

10+ Year Member



Well, here's your problem. You're using a loop to retrieve all records from the resultset, but you're only making a single assignment within the loop. So what's happening is the very last trip through the loop, that last record's value is what's being assigned to $val.

You can do two things in this case: either create an empty array to store each `name` value through each loop iteration, and then use it to create the SELECT element's OPTION set, or simply output the OPTION set within the loop. The latter is probably easier and more efficient, because you only have to use a single loop structure to make it work.

Let me give you an example using your code.


// standard query, OK
$q = "SELECT name FROM style_custom WHERE member = '$member'";
// basic call to execute the query, fine,
// but could use some troubleshooting in case it fails
$r = mysqli_query($dbc, $q);
// output the SELECT
echo '<select name="grab" id="grab">';
// a default "blank" option, if you like
echo '<option value=""></option>';
// begin looping through the resultset, creating the OPTION set
while ($row = mysqli_fetch_array($r)) {
echo "<option value='{$row['name']}'>{$row['name']}</option>";
}
// end the SELECT element
echo '</select>';

Note that the $row['name'] element is simply passed into the string that outputs the OPTION element. The curly braces surrounding it help the parser identify the array element within and not confuse the 'single quotes'.

sigh. I miss PHP bbcode tags