阻止表单多次将数据插入数据库

时间:2017-02-01 20:08:08

标签: php mysql database

尝试将表单数据插入到mysql数据库中,我的问题是当用户提交表单时数据被插入数据库两次。我知道我的第二个查询$query_file = "INSERT INTO upperbit_files...语句出错了,因为当我删除整个if循环if(mysqli_query($dbc, $query_info)){...}时,表单会按预期提交一次。

基本上我需要将数据插入2个表中。一个用于一般产品信息,另一个用于存储与该产品相关的照片,表格通过全局变量$advert_id连接。我正在使用2个单独的查询

  1. 表1:advert_sell_category1,用于一般产品信息
  2. 表2:upperbit_files,用于存储上传图片的详细信息
  3. 但由于某种原因,与一般产品信息相关的第一个查询将被插入数据库两次,具有讽刺意味的是$advert_id相同的时间。以下是我的代码和数据库截图供您理解,

    enter image description here

        if(isset($_POST['postad'])){
    
            $adtype =  $_POST['offering_type'];
            $manufacturer = mysqli_real_escape_string($dbc, $_POST['manufaturer']);
            $mediafile = mysqli_real_escape_string($dbc,$_POST['mediafile']);
    
        $GLOBALS['advrt_post_id'] = crypto_rand_secure(10, 100000);
        $query_info = "INSERT INTO advert_sell_category1(advert_id,manufacturer,image_file) 
        VALUES('$advrt_post_id','$manufacturer','$mediafile')";
        $result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
    
           if(mysqli_query($dbc, $query_info)){
        $last_id = mysqli_insert_id($dbc);
        $query_link_id = "SELECT advert_id FROM advert_sell_category1 WHERE id = '$last_id' ";
        $result_id = mysqli_query($dbc, $query_link_id);
    
        while ($row = mysqli_fetch_assoc($result_id)) {
            $link_id = $row['advert_id'];
    
           if(!empty($mediafile)){
           $media_file = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafile']));
           $media_file = array_filter($media_file);
           $media_file_size = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafilesize']));
           $media_file_size = array_filter($media_file_size);
           $media_file_type = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafiletype']));
           $media_file_type = array_filter($media_file_type);
            for ($var = 0; $var < sizeof($media_file); $var++){ 
            $query_file = "INSERT INTO upperbit_files(file,size,type,link_id) VALUES ('$media_file[$var]','$media_file_size[$var]','$media_file_type[$var]','$link_id')";
            $result_file = mysqli_query($dbc, $query_file) or die(mysqli_error($dbc));
            } 
          }
        }
      }
    

1 个答案:

答案 0 :(得分:1)

/********** Your Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));

if(mysqli_query($dbc, $query_info)){
/**********************/

请在 if 语句中查看第二次调用 mysqli_query() ,以便相同的数据插入两次。使用以下代码来解决您的问题

/********** Suggested Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));

if(mysqli_affected_rows()>0){
/**********************/