Select2 - 将多个选择写入数据库,双记录

时间:2016-11-22 07:41:22

标签: php jquery mysql ajax select2

这里有趣的问题。

我使用Select2允许用户填充具有多个值的选择框,然后将其写入数据库表。但是,在将值插入表中时,我注意到select字段的最后一个值总是写入两次。我怀疑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: 在JS代码中添加return;

1 个答案:

答案 0 :(得分:0)

问题似乎与AJAX交互有关,更具体地说是use Validator; // Static rules that don't change $v = Validator::make($data, [ 'type' => 'required|in:star_rating,review' ]); // Conditional rules that do change $v->sometimes('body', 'required|min:6', function ($input) { return $input->type === 'review'; }); // Validator failed? Return back with errors/input if ($validator->fails()) { return back()->withErrors($validator) ->withInput(); } // Proceed however you'd like with request 和SQL语句。

我将mysqli_real_escape()循环更改为此并且奇迹般地起作用,尽管更改仅包括重命名SQL变量并删除转义字符串(我后来再次添加并仍然有效)。

foreach

不确定为什么会这样,但它现在有效:)