PHP - 下拉列表填充但不会选择使用2个表

时间:2014-03-10 16:31:43

标签: php mysql selected

我已经在这个问题上工作了至少一个月,但在其他地方找不到这个问题。我知道我只是错过了一些愚蠢的东西,但是......

有2个表:biz和bizclass。 bizclass.bizclassName包含250+分类以填充下拉框。从bizclass表和更新到biz表的人口都可以工作,但是当我尝试从biz.bizClass1中选择当前数据时,下拉初始值被设置为空值“Select Class”。请帮忙。它让我疯狂。对于更多不眠之夜,我太老了!新手 - 有点熟悉php和javascript,但还没有抓住ajax。

echo "Class1: <select name ='bizClass1' id='bizClass1'/> ";

$sql = 'SELECT bizclassName FROM bizclass ORDER BY bizclassName';
$query2 = 'SELECT `bizClass1` FROM `biz` WHERE `bizID` = "'. $search .'"'; 
$clist = mysqli_query($connection,$sql); 
$num=mysqli_num_rows($clist);
$olist = mysqli_query($connection, $query2); // select  bizClass from biz 

$bizTblRecord = mysqli_fetch_assoc($clist); // option values from bizclass table to populate the dropdown
$row2 = mysqli_fetch_assoc($olist); // fetched the bizClass from biz

if ($row2['bizClass1'] == $bizTblRecord['bizclassName']){
    printf ("<option value='%s' selected >%s</option> ", $row2['bizClass1'], $row2['bizClass1']);
} else {
    printf ("<option value=''>Select Class</option> ");
}//end if


for($numrows=1; $numrows<= $num; $numrows++)
{
    // Associative array
    $row=mysqli_fetch_assoc($clist);

    printf ("<option value='%s'>%s</option>",$row['bizclassName'],$row['bizclassName']);

} //end for

echo "</select>";

// Free result set
mysqli_free_result($clist); 
mysqli_free_result($olist);

1 个答案:

答案 0 :(得分:0)

    echo "Class1: <select name ='bizClass1' id='bizClass1'/>
                         <option value=''>Select Class</option> ";

    $sql = 'SELECT bizclassName FROM bizclass ORDER BY bizclassName';
    $clist = mysqli_query($connection,$sql); 
    $num=mysqli_num_rows($clist);



    $querySEARCH = 'SELECT `bizClass1` FROM `biz` WHERE `bizID` = "'. $search .'"'; 
    $SEARCHlist = mysqli_query($connection, $querySEARCH); // select  bizClass from biz 
    $rowSEARCH= mysqli_fetch_assoc($SEARCHlist); // fetched the bizClass from biz

    for($numrows=1; $numrows<= $num; $numrows++)
    {
        // Associative array
        $row=mysqli_fetch_assoc($clist);

        if ($rowSEARCH['bizClass1'] == $row['bizclassName']){
            printf ("<option value='%s' selected >%s</option> ", $rowSEARCH['bizClass1'], $rowSEARCH['bizClass1']);
        } else {
            printf ("<option value='%s'>%s</option>",$row['bizclassName'],$row['bizclassName']);
        }//end if

    } //end for

    echo "</select>";

    // Free result set
    mysqli_free_result($clist); 
    mysqli_free_result($SEARCHlist);

如果语句必须在循环内,则将每个选项与搜索进行比较。

测试表:

BIZ

bizID   bizClass1
1       ronaldo
2       shevshenko
3       falcao
4       zidane
5       valderrama

bizclass

bizclassName
falcao
ozil
ronaldo
messi
shevshenko
valderrama
hazard
totti