dongxi8297
2015-07-10 23:45
浏览 58
已采纳

在mysqli生成的下拉框中的一行上显示多个值

Using mysqli code, I have been able to create a dropdown box using data from a mysql database. The sql statement selects the userId, f_Name, and l_Name from the database. This list is part of a form and when the user selects the name, I want to pass only the userId via the $_Post method. How can that be done? Thanks again for your help.

<select name="names">
    <option value = "">---Select---</option>
    <?php
        $queryusers = 'SELECT userID, f_Name, l_Name FROM users';
        $db = mysqli_query($mysqli, $queryusers);
        while ( $names=mysqli_fetch_assoc($db)) {
           echo "<option value='{".$names['f_Name']."}' . 
                {".$names['l_Name']."}'>".$names['f_Name']. " " .
                $names['l_Name']."</option>";
        }
    ?>
</select>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudan1123 2015-07-10 23:48
    已采纳

    Just do something like this:

    echo '<option value="'.$names['userID'].'" >'.$names['f_Name'].' '. $names['last_nm'] . '</option>';
    

    that becomes the value of the option, which is what gets submitted.

    Edit

    This is your code using this

    <select name="names">
        <option value = "">---Select---</option>
        <?php
            $queryusers = 'SELECT userID, f_Name, l_Name FROM users';
            $db = mysqli_query($mysqli, $queryusers);
            while ( $names=mysqli_fetch_assoc($db)) {
               echo '<option value="'.$names['userID'].
                '" >'.$names['f_Name'].' '. $names['last_nm'] . '</option>';
            }
        ?>
    </select>
    

    another edit to show the mysqli prepared statement example

    Assuming you are inserting these same values into a table, you'd just do it like this:

    Your mysqli connection would be something like this:

    $conn = new mysqli($host, $username, $password, $dbname)
    

    Then you'd do your insert like this (assuming userID is an autoincrement key)

    $stmt = $dbc->prepare("insert into users (userID, f_name, L_name)
                           values (NULL, ?, ?)");
    $stmt->bind_param("ss", $names['f_name'],$names['l_name'])
    $stmt->execute();
    $stmt->close();
    

    The "ss" just means both variables are strings; if they are integers you'd use i. If you are doing an update, you'd just replace any variables you'd use in the insert with those ? placeholders. It works the same way.

    Here's the manual: mysqli prepared statements

    点赞 评论

相关推荐 更多相似问题