从多个类别中获取数据

时间:2013-06-15 05:48:50

标签: php html mysql

我的数据库中有3个表,结构是

 advertisement 
 +--+-----+------------+
 |id|name |description | 
 +--+-----+------------+
 | 1| Name| some text  |
 +--+-----+------------+


Categories
+---+-------------+
|id |category_name|
+---+-------------+ 
|2  |category 1   | 
|3  |category 2   | 
|4  |category 3   | 
+---+-------------+

并且最后一个表是我的广告存储位置,我想让多个类别选择表格结构是

+---------+------+
|advert_id|cat_id|
+---------+------+
|    1    |   2  |
|    1    |   3  |
+---------+------+

我将数据插入我的数据库但我无法获取数据以便在此功能中进行编辑

<select>
<select name="cat[]" multiple>
<option value="id" selected>Category 2</option>
<option value="id" selected>Category 3</option>
<option value="id" selected>Category 3</option>
</select>

我写这段代码只显示一个选定的类别

<?php
function advert_select($advert_id){
    $data = array();
    $query = mysql_query("SELECT *FROM `advert_to_area` WHERE `advert_id`=$advert_id");
    while($row = mysql_fetch_assoc($query)){
        $data[] = array(
        'area_id'   => $row['area_id']
        );

    }   
    return $data;
}

function get_advert_cat(){
    $data = array();
    $query = mysql_query("SELECT *FROM `areas`");
    while($row = mysql_fetch_assoc($query)){
        $data[] = array(
        'id'        => $row['id'],
        'name'      => $row['area_name']
        );
    }
    return $data;
}
?>
<?php
echo '<select name="areas[]" multiple>';
$data = advert_select($advert_data['id']);
$areas = get_advert_cat();
foreach($data as $d){
    $area_id = $d['area_id'];

}
foreach ($areas as $area){

    if($area['id']==$area_id){
        echo '<option value="' . $area['id'] .'" selected>' . $area['name'] . '</option>';
    }else{
        echo '<option value="' . $area['id'] .'" >' . $area['name'] . '</option>';
    }
}

echo "</select>";
?>

你能告诉我,我做错了什么,或者我能做些什么来展示我给出的例子。感谢

1 个答案:

答案 0 :(得分:0)

如果我理解正确,这应该有用。

<?php
echo '<select name="areas[]" multiple>';
$data = advert_select($advert_data['id']);
$areas = get_advert_cat();
$area_id = array();
foreach($data as $d){
    $area_id[] = $d['area_id'];

}
foreach ($areas as $area){

    if(in_array($area['id'],$area_id)){
        echo '<option value="' . $area['id'] .'" selected>' . $area['name'] . '</option>';
    }else{
        echo '<option value="' . $area['id'] .'" >' . $area['name'] . '</option>';
    }
}

echo "</select>";
?>