0

i want to echo selected data from database as default

( if the user selected country USA in the registration when he want to edit his data , the list choose USA as default and if he want to choose another country and change his first selection he can do that )

<select id="exam_ch" name="exam_ch" class="select_list_exams">
    <?php
        $sql="SELECT * FROM `exam` WHERE `avilable` = 1 " ;
        $result=$ conn->query($sql);
        while($row = $result->fetch_assoc()) {
            echo "<option value=".$row['id'].">"
                . $row['date']." The Time"
                . $row['time']."</option>";
        }
    ?>
</select>
  • What do you want to do? – someOne May 24 '15 at 19:17
  • i want to ( if the user selected country USA in the registration when he want to edit his data , the list choose USA as default and if he want to choose another country and change his first selection he can do that ) – Abdelrahman Magdy May 24 '15 at 21:31
  • Please note that though this was closed, the referred answer is using deprecated code (`mysql_`) extensions. keep doing what you are doing :) – nomistic May 25 '15 at 13:26

2 Answers2

0

In the option tag, before it closes, add a if statement to check if $row["id"] equals to the selected value of the user, if so, echo out selected.

For example, an option tag for usa with id 1 where the selected id by user is 1 should be: usa

Ron Dadon
  • 2,625
  • 1
  • 13
  • 26
0

You can just do something like this, if the row you are trying to match up is the submitted id

    $id = $_POST['id'];

    $result=$ conn->query($sql);
    while($row = $result->fetch_assoc()) {

        if ($row['id'] == $id) {

            $selected = 'selected="selected"';
        }
        else {
            $selected = '';
        }   

        echo '<option value="'.$row['id'].'" '. $selected . '>"'

            . $row['date'].' The Time' 
            . $row['time'].'</option>';
    }
nomistic
  • 2,857
  • 4
  • 18
  • 36