Geoff
Geoff

Reputation: 5

PHP - Drop down as variable not being passed

I am trying to get a variable from a drop down list. The drop down list is fully populated using a mysql query, and demonstrates the correct information I'd be expecting. I have found an example online (the bottom one) which does exactly what I want it to, but my example (the top one) is not. I presume this is something to do with the fact that it is populated by database info rather than plain text, but I can't work out precisely what is wrong.

This is what populates the table and is working fine.

<?php
$sql="SELECT athleteforename, athletesurname FROM athletes WHERE userID='$userID'"; 
$result=mysql_query($sql); 
$options=""; 
while ($row=mysql_fetch_array($result)) { 
$forename=$row["athleteforename"]; 
$surname=$row["athletesurname"];         
$options.="<option value='$id'>" . $forename . ' ' . $surname . '</option>';
}
?> 

This one echos "name is set to" but then no value is given. It is full of the correct names, though.

<form action="" method="post">
<select NAME="name" onchange="this.form.submit();"> 
<?=$options?>
</select>
</form>
<?php 
if (isset($_POST['name'])) {echo 'name is now set to ' . $_POST['$name'];} 
?>

This one works exactly as I want the top one to.

<form action="" method="post"> 
<select name="var" onchange="this.form.submit();"> 
<option value="1">var 1</option> 
<option value="2">var 2</option> 
<option value="3">var 3</option> 
<option value="4">var 4</option> 
<option value="5">var 5</option> 
</select> 
</form> 

<?php 
if (isset($_POST['var'])) {echo 'var is now set to ' . $_POST['var'];} 
?>

Upvotes: 0

Views: 58

Answers (3)

JerkShakespear
JerkShakespear

Reputation: 1

You are not declaring the variable right . $varaible =['value'] ; value is generally the dropdown value . for eg: var 1 so, when you echo $variable it will show the value var 1 .

Use this and hope it solves the problem .

Upvotes: 0

ahuemmer
ahuemmer

Reputation: 2049

I think, it is this line:

$options.="<option value='$id'>" . $forename . ' ' . $surname . '</option>';

Where is $id coming from? Seems to be uninitialized.

You could also have a look at the output HTML generated by your script to find the difference to the working example you found.

Another thing:

Your code will produce HTML like (if you had $id=3): <option value='3'>. That's no so nice. ;) Browsers will probably accept it, but "good" HTML should use "s. So if you have the $id initialized propery, the line above should rather look like this:

$options.='<option value="$id">' . $forename . ' ' . $surname . '</option>';

Edit:

Konstantinos Botonakis found another issue: $_POST['$name']; should be $_POST['name']; IMHO.

Upvotes: 1

Konstantinos
Konstantinos

Reputation: 417

The problem is because you have:

$_POST['$name'];

you should change it:

$_POST[$name];

Upvotes: 0

Related Questions