Daniel
Daniel

Reputation: 153

Access variable from populated dropdown select (PHP)

<select name="shortcut">
<?php
$sql= "SELECT * FROM subject WHERE id_ped = $id_ped";
$vysledek0 = mysqli_query($con, $sql);
$count0 = mysqli_num_rows($vysledek0);
   for($i=0;$i<$count0;$i++){
$row= mysqli_fetch_row($vysledek0);
echo "<option value=\"shortcut\">" . $row[1] . "</option>";"<br>";
   }
?>
</select>

This gives me dropdown list where I can select data from certain table.

But I have trouble accessing the data later - for example like this:

<?php   $shortcut = $_POST['shortcut'];
                    echo $shortcut;
?>

It doesn´t take in the list item but instead it takes the string ´shortcut´.

How do I use the list items as variable from this point?

Upvotes: 0

Views: 189

Answers (2)

Ahsan
Ahsan

Reputation: 4154

You need to set the value of the option for it to be posted:

<select name="shortcut">
<?php
$sql= "SELECT * FROM subject WHERE id_ped = $id_ped";
$vysledek0 = mysqli_query($con, $sql);
$count0 = mysqli_num_rows($vysledek0);
   for($i=0;$i<$count0;$i++){
$row= mysqli_fetch_row($vysledek0);
echo "<option value='" . $row[1] . "'>" . $row[1] . "</option>";"<br>";
   }
?>
</select>

Then on the server side:

<?php   
    $shortcut = $_POST['shortcut'];
    echo $shortcut;
?>

However I personally would prefer writing the above code in the following style. Just in case if you like it:

<?php
    $sql= "SELECT * FROM subject WHERE id_ped = $id_ped";
    $vysledek0 = mysqli_query($con, $sql);
    $count0 = mysqli_num_rows($vysledek0);
    $items = array();

    for($i=0; $i<$count0; $i++) {
        $row = mysqli_fetch_row($vysledek0);
        array_push($items, $row[1]);
    }
?>

<select name="shortcut">
<?php foreach($items as $value): ?>
    <option value="<?php echo $value ?>"><?php echo $value ?></option>
    <br>
<?php endforeach ?>
</select>

Upvotes: 1

Nicolo L&#252;scher
Nicolo L&#252;scher

Reputation: 603

try to replace the \" with '. It should work that way

Upvotes: 1

Related Questions