简体   繁体   中英

Output data from database with PHP into dropdown box

I have a form designed with bootstrap style and I want to retrieve data from a database into a drop-down list. I tried this code, but I get a list with no text.

    <div class="form-group"><label class="col-sm-2 control-label">Location</label>
    <div class="col-sm-8"><select class="form-control m-b" name=Location>
    <?php
    $mysqli = new mysqli( 'localhost', 'cshrnaf_user2', '=cXlIBsdMkdr', 'cshrnaf_mis_db' );
    /* check connection */
    if (mysqli_connect_errno())
    {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
    }
    $query = "SELECT * FROM adhoc";
    $result = mysqli_query($mysqli,$query);
    while($rows = mysqli_fetch_assoc($result))
    {
    echo "<option value=" . $rows['Aim'] . "></option>";

    echo "<option value='{".$d['Aim']."}'>".$d['Aim']."</option>";
    }
?> 
  1. $d is never mentioned before you try to echo it, so what is it's content?
  2. echo "<option value=" . $rows['Aim'] . "></option>"; has two issues: firstly, the value is not encased in quotes, and secondly, there is no content in the tag, so no text will output.

Try changing your while to:

while($rows = mysqli_fetch_assoc($result)){
    echo "<option value='{$rows['Aim']}'>{$rows['Aim']}</option>";
}

As long as $rows['Aim'] contains the content you wish to output, this should work.

     // cat  is array fetch from database

     <select name="cat" id="cat_id" style="width:170px" value="<?php echo $_POST['cat']; ?>">


<option value="0"></option>
    <?php
    foreach ($cat as $row) {
        ?>
                                                <option value="<?php echo $row->tag_cat_id ?>" ><?php echo $row->tag_cat_name ?></option>
        <?php }
    ?>
                                        </select>
                                            </select>

You should select database in your file.Above you only connect to your localhost.And you should use variable name $rows for all fetch values

if (!mysqli_select_db("mydbname")) {
    echo "Unable to select database: " . mysqli_error();
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM