当用户在选择字段中选择新选项时,如何运行mysql查询?

时间:2012-09-18 18:12:27

标签: php javascript mysql html css

我希望有一个列出产品类别的选择框。选择类别后,我想同时从数据库中选择该类别中的产品。我是否需要在此应用程序中使用AJAX?关于这样做的任何例子?这是我正在使用的代码:

这些函数构建了每个选择字段的选项。

function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
        FROM tbl_category
        ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
    list($id, $parentId, $name) = $row;

    if ($parentId == 0) {
        // we create a new array for each top level categories
        $categories[$id] = array('name' => $name, 'children' => array());
    } else {
        // the child categories are put int the parent category's array
        $categories[$parentId]['children'][] = array('id' => $id, 'name' =>   
$name); 
    }
}   

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
    $name     = $value['name'];
    $children = $value['children'];

    $list .= "<option value=\"$key\"";
    if ($key == $catId) {
        $list.= " selected";
    }

    $list .= ">$name</option>\r\n";

    foreach ($children as $child) {
        $list .= "<option value=\"{$child['id']}\"";
        if ($child['id'] == $catId) {
            $list.= " selected";
        }

        $list .= ">&nbsp;&nbsp;{$child['name']}</option>\r\n";
    }
}

return $list;
}

/ *     构建无线电选项的产品选项列表    * /

function buildProductOptions($catId = 0)
{
$sql = "SELECT pd_id, pd_name, cat_id
    FROM tbl_product
    WHERE cat_id = $catId 
    ORDER BY pd_name";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$numProduct = dbNumRows($result);

$products = array();
while($row = dbFetchArray($result)) {
    list($id, $name) = $row;
        // we create a new array for each top level categories
        $products[$id] = array('name' => $name);
}   

// build combo box options
$list = '';
foreach ($products as $key => $value) {
    $name     = $value['name'];

    $list .= "<option value=\"$key\"";

    $list .= ">$name</option>\r\n";

}

return $list;

}

这是选择字段的页面:

$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;

$categoryList = buildCategoryOptions($catId);
$productList = buildProductOptions($catId);

<!--- Category Select --->
<select name="cboCategory" id="cboCategory" class="box">
   <option value="" selected>-- Choose Category --</option>
<?php
        echo $categoryList;
 ?>  
</select>

<!--- Products Select : category is changed the products need to be from selected cat -    
 -->

<select name="selectOptions" id="selectOptions" class="box" multiple="multiple" >
   <option>--Pick the other options--</option>
<?php
    echo $productList;
 ?> 
</select>

0 个答案:

没有答案