Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

treeyon 94
treeyon 94
14,715 Points

Need help to echo content of database into a textarea and a selectbox

Hi, i want to echo the content of my mysql database into a selectbox "How does the selectbox know which year to choose?" <?php require 'dbconnect.php'; $sqlq = $dbh->prepare("SELECT * FROM docs WHERE ID = 2"); $sqlq->execute(); $currentDocument = $sqlq->fetchAll();
?>

            <div class="form-group pubyear-input-container">
                <label for="publication" id="pubyear">Ver&ouml;ffentlichungsjahr</label>
                    <select name="year" id="year" class="form-control">

                    <?php
                    for ($i=1900; $i <= 2015; $i++) { 
                    echo "<option>" . $i . "</option>"; 
                    }
                    ?>

                    </select>
            </div>

4 Answers

Codin - Codesmite
Codin - Codesmite
8,600 Points

Are you reffering on how to choose the default selected option in the selectbox based on your database data?

For example:

<?php
$selectedyear = 1950;
?>

<select name="year" id="year" class="form-control">
    <?php
    for ($i=1900; $i <= 2015; $i++) { 
    ?>
        <option<?php if ($i === $selectedyear){echo " selected"}?>><?php echo $i; ?></option>
    <?php
    }
    ?>
</select>

This will check the value of each option being added via the for loop against the set $selectedyear value. If it gets a match it will echo " selected" into the matching option which will output as

<option selected>1950</option> 

making it the default selected option in the list.

Tobias Mahnert
Tobias Mahnert
89,414 Points

Have you tried this?

                     <?php
                    for ($i=1900; $i <= 2015; $i++) { 
                    ?> <option> <?php echo $i; ?> </option> <?php
                    }
                    ?>
Jose Torres
Jose Torres
1,836 Points

Well it depends of the content of the database table you want to display. At least you should give example of the structure of the table.

treeyon 94
treeyon 94
14,715 Points

Allready fixed the problem. Thanks