Search code examples
phphtmldropdownbox

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?


Solution

  • 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>