2016-11-22 22 views
0

這裏有趣的問題。Select2 - 寫入多重選擇到數據庫中,雙記錄

我正在使用Select2來允許用戶填充具有多個值的選擇框,然後將其寫入數據庫表中。但是,在將值插入表中時,我注意到選擇字段的最後一個值始終寫入兩次。我懷疑foreach循環有問題,但不知道如何解決這個問題。

選擇字段是單擊SAVE按鈕後模式的一部分通過AJAX發送到我的ajax.php文件,其中插入處理。同樣的方法在整個網站上多次部署沒有問題,只有在其字段爲multiple時纔會出現問題。

HTML

<!-- Department --> 
<label>Department Name:</label> 
<div class="input-group"> 
    <span class="input-group-addon"><i class="fa fa-bars"></i></span> 
    <input type="text" class="form-control" id="addDeptName" name="addDeptName" /> 
</div> 
<!-- /.Department --> 

<p> </p> 

<!-- Positions --> 
<label>Department Positions:</label> 
<div class="input-group"> 
    <span class="input-group-addon"><i class="fa fa-briefcase"></i></span> 
    <select class="form-control select2" style="width:100%;" id="addDeptPositions" name="addDeptPositions" multiple> 
     <option value="Option1">Option1</option> 
     <option value="Option2">Option2</option> 
     <option value="Option3">Option3</option> 
     <option value="Option4">Option4</option> 
    </select> 
</div> 
<!-- /.positions --> 

JS

// ADD NEW RECORD TO DATABASE   
$("#NewDepartmentButton").click(function() { 
    $("#addDeptName").focus(); 

    // check that input fields are not empty 
    if($("#addDeptName").val()!="" && $("#addDeptPositions").val()!="") { 

     $.ajax({ 
      url: "../../plugins/MySQL/ajax_action.php", 
      type: "POST", 
      //async: true, 
      data: { action:"new_department",Department_Name:$("#addDeptName").val(),Department_Positions:$("#addDeptPositions").val()}, // form data to post goes here as a json object 
      dataType: "html",   

      success: function(data) { 
       $('#department_output').html(data); 
       drawVisualization(); 
      }, 
     }); 
    } else { 
     //notify the user they need to enter data 
     alert("Please enter a valid Department Name."); 
     return; 
    } 

    // close modal and refresh page 
    $('#NewDepartmentModal').modal('hide'); 
    setTimeout(function(){location.reload()}, 2000); 

    // Reload Datatables 
    //$('#department_table').DataTable().ajax.reload(); 

    // refresh entire website 
    //location.reload(); 

    return; 
}); 

PHP

if(isset($_POST['action']) && ($_POST['action']=='new_department')) { 

    // include connection details 
    include 'connect_db.php'; 

    //Open a new connection to the MySQL server 
    $db = new mysqli($dbhost,$dbuser,$dbpass,$dbname); 

    //Output any connection error 
    if ($db->connect_error) { 
     die('Error : ('. $db->connect_errno .') '. $db->connect_error); 
    } 

    // get variables and sanitize 
    $addDeptName = mysqli_real_escape_string($db,$_POST['Department_Name']); 
    $addDeptPositions = $_POST['Department_Positions']; 

    // create new record 
    foreach ($addDeptPositions as $c) { 
     $sql = "INSERT INTO `qci_departments` (`Department`,`Positions`) VALUES ('".$addDeptName."', '".mysqli_real_escape_string($db, $c)."')"; 
     $db->query($sql); 
    } 

    if (!$db->query($sql)) { 
     echo " 
      <div class=\"alert alert-danger alert-dismissible\"> 
       <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button> 
       <h4><i class=\"icon fa fa-ban\"></i> Error!</h4> 
       There was an error while excuting this query.<br /> 
       (" . $db->errno . ") " . $db->error . " 
       </div>"; 
    } 

    echo " 
     <div class=\"alert alert-success alert-dismissible\"> 
      <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button> 
      <h4><i class=\"icon fa fa-check\"></i> Alert!</h4> 
      Success, record updated successfully. Refreshing database now... 
     </div>"; 

    //close connection 
    $db->close(); 

} 

數據庫結果: 如。 enter image description here

編輯:選擇值看起來 問題似乎涉及到,因爲這個數組提交的是什麼樣的:

Array ([0] => Accounting Manager [1] => Accounts Receivable Officer) Array ([0] => Accounting Manager [1] => Accounts Receivable Officer) 
如果位置「客戶經理」和「應收賬款官」,從多個領域的選擇

編輯2: addded一個return;的JS代碼

+1

打印陣列'$ addDeptPositions'並粘貼問題。如果添加,也粘貼select2 jQuery代碼。 – RJParikh

+0

如果您使用select with multiple選項,您是否認爲'name =「addDeptPositions」'應該是'name =「addDeptPositions []」' –

+0

@HappyCoding當通過'

'元素直接提交時,是的。不過,我通過AJAX提交。如果我在選擇名稱中添加'[]',$ _POST ['Department_Positions']'變量不再被識別。 – Armitage2k

回答

0

這個問題似乎已經與AJAX的互動,更特別是與mysqli_real_escape()和SQL語句。

我將foreach循環更改爲此,它奇蹟般地工作,雖然更改只包括重命名SQL變量和刪除轉義字符串(我後來再次添加並仍然有效)。

// create new record 
foreach ($addDeptPositions as $c) { 
    $sql2 = "INSERT INTO `qci_departments` (`Department`,`Positions`) VALUES ('".$addDeptName."', '".mysqli_real_escape_string($db,$c)."')"; 
    $db->query($sql2); 
} 

不知道這是爲什麼,但它現在的作品:)

+0

您還可以在Department字段中添加唯一索引。它將確保不會添加具有相同的Department字段值的行。 –

相關問題