使用MySQL数据库中的多个选项预填充下拉菜单

时间:2013-08-20 16:04:28

标签: php mysql drop-down-menu

新手在这里......我试图改编here

的代码

列表已正确填充,但我无法预先选择。我究竟做错了什么?提前谢谢!

$q = "SELECT cat_id FROM category_user WHERE cat_id=$d";
        while ($row = mysqli_fetch_array($q)) {
            $cat = (int)$row['cat_id'];
        }
        $q = "SELECT cat_id, cat FROM category";        
        $r = mysqli_query ($dbc, $q);
        if (mysqli_num_rows($r)> 0) {
            while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
                echo "<option value=\"$row[0]\"";
                $selected = '';
                $cid=(int)$row[0];
                if ($cid=$cat) {
                    $selected='selected="selected"';
                    echo $selected;
                echo ">$row[1]</option>\n";
                }else{


                //Check for stickyness
                if (isset($_POST['category'])&&($_POST['category']== $row[0])) 
                echo 'selected="selected"';
                echo ">$row[1]</option>\n";
            }
            }
        }

 category
 ---------------
 |cat_id | cat  |
 ---------------


 category_user
 -------------------------
 |cu_id | user_id | cat_id|
 -------------------------

3 个答案:

答案 0 :(得分:0)

为什么代码过于复杂。你可以试试这样的东西

<?php
    $result = mysqli_query($dbc, "SELECT cat_id, cat FROM category");
    if ($result) {
        echo "<select name='whatever_you_want'>";
        while ($row = mysqli_fetch_array($result)) {
            echo "<option value='{$row[0]}'";
            if (intval($row[0]) == intval($cat_id)) {
                echo " selected";
            }
            echo ">{$row[1]}</option>";
        }
        echo "</select>";
    }
?>

答案 1 :(得分:0)

if($cid=$cat){

应该是

if($cid==$cat){

$cid=(int)$row[0];

(int)是不必要的,因为会自动比较字符串到int。

答案 2 :(得分:0)

想出来。 foreach循环预选下拉菜单的所有内容。问题主要是从mysql表中获取数组以进行迭代选择。最后一块拼图是$ cats之后的括号[]。

感谢您的帮助,对不起,我不太清楚我想要完成的事情。我的坏。

<p><select class=\"box\" name=\"wkType[]\" multiple=\"multiple\">";
$q = "SELECT cat_id FROM category_user WHERE user_id=$d";
$r = mysqli_query ($dbc, $q);
    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { 
    $cats[]=$row['cat_id'];                     
}
    $q = "SELECT cat_id, cat FROM category";        
    $r = mysqli_query ($dbc, $q);
    if (mysqli_num_rows($r)> 0) {
        while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
            echo "<option value=\"$row[0]\"";
            foreach ($cats as $key =>$cat) {
        if ($row[0]==$cat){
        echo 'selected="selected"';
                    //Check for stickyness
        if (isset($_POST['category'])&&($_POST['category']== $row[0])) 
            echo 'selected="selected"';
        }
                  }
        echo ">$row[1]</option>\n";
          }
}else{
echo '<p>Please select a category.</p>';    
}   
echo "</select></p>";