0

新手在这里...我试图从这里调整我的代码

该列表已正确填充,但我无法对其进行预选。我究竟做错了什么?提前致谢!

$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|
 -------------------------
4

3 回答 3

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>";
于 2013-08-21T03:55:20.020 回答
0
if($cid=$cat){

应该

if($cid==$cat){

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

(int)是不必要的,因为 string 到 int 是自动比较的。

于 2013-08-20T16:18:52.773 回答
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>";
    }
?>
于 2013-08-20T16:15:19.157 回答