這裏有趣的問題。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\">×</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\">×</button>
<h4><i class=\"icon fa fa-check\"></i> Alert!</h4>
Success, record updated successfully. Refreshing database now...
</div>";
//close connection
$db->close();
}
編輯:選擇值看起來 問題似乎涉及到,因爲這個數組提交的是什麼樣的:
Array ([0] => Accounting Manager [1] => Accounts Receivable Officer) Array ([0] => Accounting Manager [1] => Accounts Receivable Officer)
如果位置「客戶經理」和「應收賬款官」,從多個領域的選擇
編輯2: addded一個return;
的JS代碼
打印陣列'$ addDeptPositions'並粘貼問題。如果添加,也粘貼select2 jQuery代碼。 – RJParikh
如果您使用select with multiple選項,您是否認爲'name =「addDeptPositions」'應該是'name =「addDeptPositions []」' –
@HappyCoding當通過'