peace_love
peace_love

Reputation: 6461

How can my selectbox display "nothing selected" when a value is empty?

Hi I have a select box which works fine. The value of $person is always selected.

                 <select class="selectpicker form-control" name="person">

                    <?php 
                    $pdo = Database::connect();
                    $sql = 'SELECT * FROM user ORDER BY id ASC';
                    foreach ($pdo->query($sql) as $row) {
                        echo('<option');?>
                        <?php 
                        if ($person == $row['name']) 
                        echo 'selected '; 
                        echo('value="'.$row['name'].'">'.$row['name'].'</option>');
                    }
                    Database::disconnect();
                    ?>
                    <option></option>
                    </select>

But what I do not achieve is: If $person is empty, then the box should display nothing selected.

Upvotes: 0

Views: 302

Answers (2)

Steve
Steve

Reputation: 20469

Simply check if person is empty, and if so, output an option tag with the required wording:

<select class="selectpicker form-control" name="person">
    <?php 
    $pdo = Database::connect();
    $sql = 'SELECT * FROM user ORDER BY id ASC';
    foreach ($pdo->query($sql) as $row) {
        echo '<option';
        if ($person == $row['name']) 
             echo 'selected '; 
        echo 'value="'.$row['name'].'">'.$row['name'].'</option>';
    }
    if(empty($person))
        echo '<option selected >nothing selected</option>';
    Database::disconnect();?>
</select>

On another note, having database code intertwined with html is hard to read and maintain, it would be better to separate this, either into separate files, or at least have all the db code at the top of the file, and only have layout logic in the html

Upvotes: 1

Mayous
Mayous

Reputation: 2148

You should had a first option with an unvalid value like :

<select class="selectpicker form-control" name="person">
<option value="0">Choose a person</option>
                <?php 
                $pdo = Database::connect();
                $sql = 'SELECT * FROM user ORDER BY id ASC';
                foreach ($pdo->query($sql) as $row) {
                    echo('<option');?>
                    <?php 
                    if ($person == $row['name']) 
                    echo 'selected '; 
                    echo('value="'.$row['name'].'">'.$row['name'].'</option>');
                }
                Database::disconnect();
                ?>
                <option></option>
                </select>

By doing this, if no field is selected, the first one will be display !

Upvotes: 1

Related Questions