Using php variable in html select forms name

Here’s a question for all you great php programmers.
What I want to do is use a variable username as the name of a select input of a form.
I.E

echo"<select name='$user'>";

Of course this code doesn’t work though I feel sure that there must be a way to do this.
Anyone know it?:smiley:

You want to display the username under select box items?
or any text box value?

The name of a <select> is just how you’ll refer to that input in your code. The value must come from options.


<select name="my_field">
   <option value="1">Helicopter</option>
   <option value="2">Bus</option>
   <option value="3">Unicycle</option>
</select>

$_POST[‘my_field’] will be 1, 2 or 3 depending on what was selected.

I doubt you want a dynamically named select field. If you want to preselect a value in a list you need to give that option a selected attribute:


$user = 'bob';
$users = array('helen', 'alan', 'bob', 'michelle', 'sarah', 'anna');

$select = "<select name='user'>\
";

foreach($users as $u) {
   $s = ($u == $user) ? 'selected' : '';
   $select .= "<option value='$u' $s>$u</option>\
";
}
echo $select . "</select>";

Actually that IS what I want! I am trying to use a dynamically created name for the select field!

Then what you had originally will work. What HTML does that output?

Here is how I am trying to receive what I want

while ($i < $num) {
$user=mysql_result($result,$i,"user");
if (isset($_POST['$user'])){
$level = ($_POST['$user']);
echo "$level";
}else{
echo "$user not recieved";
}
$i++;
}

Though I get ‘user not received’

Awkward looking code, there could be more problems with it, but one is that you’re referring to $_POST[‘$user’]

Those single quotes around $user will cause it to be treated as a literal string, not a variable, so it’ll never be set.


$var = 'Hello';
echo '$var'; //outputs $var not Hello
echo $var; //outputs Hello

Of course that was the problem.
Seems to work now.
Thanks!
And yes my code may look awkward. If you can suggest a better way I am always open to correction as I am quite new to php and have been learning it from books.