【发布时间】:2016-11-22 07:41:22
【问题描述】:
这里有一个有趣的问题。
我使用 Select2 允许用户用多个值填充选择框,然后将这些值写入数据库表中。但是,在将值插入表时,我注意到选择字段的最后一个值总是被写入两次。我怀疑foreach 循环有问题,但不知道如何解决。
选择字段是模式的一部分,在单击“保存”按钮后,它会通过 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:
在 JS 代码中添加了return;
【问题讨论】:
-
打印数组
$addDeptPositions并将其粘贴到有问题的地方。如果添加,还要粘贴 select2 jquery 代码。 -
我们无法解决该问题,因为您没有指定从何处提交表单数据。从哪里获取 $_POST['Department_Positions']`。
-
请附上ajax代码以便我们识别。
-
您的代码看起来很完美。不调试就无法判断,只需尝试一次删除
async: true并检查。 -
在完成onClick函数之前在js代码的最后一行添加return
标签: php jquery mysql ajax select2