与在数据库中存储多个选择选项相关的问题

时间:2018-05-24 12:52:53

标签: php mysql

我已经编写了将多个选择选项(类别)保存到数据库中的代码,但不知怎的,它没有正常工作,也没有将多个类别保存到数据库中。

以下是我的代码:

//数据插入

$data = array( 
          //'cat_id'  =>   implode(', ',$_POST['cat_id']),
    'cat_id'  =>  $_POST['cat_id'],
    'coupon_code'  =>  $_POST['coupon_code'],
    'activation_link'  =>  $_POST['activation_link'],     
          'coupon_image'  =>  $coupon_image,
          'brand_name'  =>  addslashes($_POST['brand_name']),     
          'brand_logo'  =>  $brand_logo,
          'sort_desc'  =>  addslashes($_POST['sort_desc']),
          'long_desc'  =>  addslashes($_POST['long_desc'])
    );

$qry = Insert('tbl_coupons',$data);


//And code for select option :-

<select name="cat_id" id="cat_id" class="select2" multiple="multiple" required >
                        <option value="">--Select Category--</option>
          <?php
          while($cat_row=mysqli_fetch_array($cat_result))
          {
          ?>         
          <option value="<?php echo $cat_row['cid'];?>"><?php echo $cat_row['category_name'];?></option>             
          <?php
          }
          ?>
                      </select>

///功能代码: -     //#Insert Data

function Insert($table, $data){

    global $mysqli;
    //print_r($data);

    $fields = array_keys( $data ); 
    $values = array_map( array($mysqli, 'real_escape_string'), array_values( $data ) );

  //echo "INSERT INTO $table(".implode(",",$fields).") VALUES ('".implode("','", $values )."');";
   //exit; 
    mysqli_query($mysqli, "INSERT INTO $table(".implode(",",$fields).") VALUES ('".implode("','", $values )."');") or die( mysqli_error($mysqli) );

}

1 个答案:

答案 0 :(得分:1)

选择选项中的问题名称将名称更改为数组,如

<select name="cat_id[]" id="cat_id" class="select2" multiple="multiple" required >

并且cat_id是数组类型,因此内爆并分配类似

$data = array( 
          'cat_id'  =>   implode(', ',$_POST['cat_id']),
          //'cat_id'  =>  $_POST['cat_id'],
          'coupon_code'  =>  $_POST['coupon_code'],
          'activation_link'  =>  $_POST['activation_link'],     
          'coupon_image'  =>  $coupon_image,
          'brand_name'  =>  addslashes($_POST['brand_name']),     
          'brand_logo'  =>  $brand_logo,
          'sort_desc'  =>  addslashes($_POST['sort_desc']),
          'long_desc'  =>  addslashes($_POST['long_desc'])
    );

$qry = Insert('tbl_coupons',$data);

还有一件事从您的查询中移除;,如

mysqli_query($mysqli, "INSERT INTO $table(".implode(",",$fields).") VALUES ('".implode("','", $values )."')") or die( mysqli_error($mysqli) );