动态表单将空值插入数据库

Dynamic form inserting blank values into database

我在将表单数据添加到数据库时遇到了一些问题。表单根据先前选择的值动态变化,但在插入数据库期间,值是空白的,但我无法弄清楚哪里出错了。它们似乎通过了验证值不为空的验证检查。

如有任何帮助,我们将不胜感激。

干杯

HTML形式

              <form class="form-horizontal" action="php_action/create.php" method="POST" id="createHostForm">

              <div class="modal-body">
                <div class="messages"></div>

                          <div class="form-group">
                            <label for="crm" class="col-sm-2 control-label">CRM No.</label>
                            <div class="col-sm-10">
                                 <select class="form-control form-control-md" id="crm">
                                    <option selected disabled>Select </option>
                                    <?php foreach($customers as $customer): ?>
                                    <option value="<?php echo $customer['crm']; ?>"><?php echo $customer['crm']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="package_ref" class="col-sm-2 control-label">Package</label>
                            <div class="col-sm-10">
                                <select class="form-control form-control-md" id="package_ref">
                                    <option>Select </option>
                                </select>
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="hostname" class="col-sm-2 control-label">Hostname</label>
                            <div class="col-sm-10">
                                <select class="form-control form-control-md" id="hostname">
                                    <option>Select </option>
                                </select>
                            </div>
                          </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
              </div>
              </form>

    <script>
    $(document).ready(function() {

        // ------------------ [ Customer dropdown Change Event ] --------------
        $("#crm").change(function() {
            var customerId = $(this).val();
            $("#package_ref").fadeIn('slow');

            $.ajax({
                url: 'process-controller.php',
                type: 'POST',
                data: {
                    custId: customerId
                },
                dataType: "JSON",

                success: function(result) {
                    var items = "";
                    $("#package_ref").empty();
                    $("#hostname").empty();

                    $("#package_ref").append(
                        "<option selected disabled> Select </option>");
                    $("#hostname").append(
                        "<option selected disabled> Select </option>");

                    $.each(result, function(i, item) {
                        $("#package_ref").append("<option value='" + item
                            .package_ref + "'>" + item.package_ref +
                            "</option>");
                    });
                }
            });
        });


        // ------------- [ Package Dropdown Change ] ---------------

        $("#package_ref").change(function() {
            var packageId = $(this).val();
            $(this).fadeIn();

            $.ajax({
                url: './process-controller.php',
                type: 'POST',
                data: {
                    packId: packageId
                },
                dataType: 'JSON',

                success: function(result) {
                    var item = "";
                    $("#hostname").empty();

                    $.each(result, function(i, item) {
                        $("#hostname").append("<option value='" + item
                        .hostname + "'>" + item.hostname +
                            "</option>");
                    });
                }
            });
        });
    });
    </script>

进程-controller.php

<?php
    require_once './data-controller.php';

    if(isset($_POST['custId'])) {
        $custId              =           $_POST['custId'];
        $dController         =           new DataController();
        $customers          =           $dController->packageListing($custId);
        echo json_encode($customers);
    }
    elseif(isset($_POST['packId'])) {
        $packId              =           $_POST['packId'];
        $dController         =           new DataController();
        $hostnames             =           $dController->hostnameListing($packId);
        echo json_encode($hostnames);
    }
?>

数据-controller.php

<?php
    include_once './db-config.php';

    class DataController {
        //  ------------ [ Customer Listing ] ------------------------
            public function getCustomers() {
                $data            =           array();
                $db              =           new DBController();
                $conn            =           $db->connect();
                $sql             =           "SELECT DISTINCT crm FROM assets";
                $result          =           $conn->query($sql);
                if($result->num_rows > 0) {
                    $data        =           mysqli_fetch_all($result, MYSQLI_ASSOC);
                }
               $db->close($conn);
               return $data;
            }

        //  ------------- [ Package Listing ] -----------------------
            public function packageListing($customerId) {
                $data           =            array();
                $db             =            new DBController();
                $conn           =            $db->connect();
                $sql            =            "SELECT DISTINCT package_ref FROM assets WHERE crm = '$customerId'";
                $result         =            $conn->query($sql);
                if($result->num_rows > 0) {
                    $data       =            mysqli_fetch_all($result, MYSQLI_ASSOC);
                }
                $db->close($conn);
                return $data;
            }

        // --------------- [ Hostname Listing ] -------------------------
            public function hostnameListing($packageId) {
                $data           =           array();
                $db             =           new DBController();
                $conn           =           $db->connect();
                $sql            =           "SELECT hostname FROM assets WHERE package_ref = '$packageId'";
                $result         =           $conn->query($sql);
                if($result->num_rows > 0) {
                    $data       =           mysqli_fetch_all($result, MYSQLI_ASSOC);
                }
                $db->close($conn);
                return $data;
            }
    }
?>

php_action/create.php

<?php

require_once 'db_connect.php';

//if form is submitted
if($_POST) {

        $validator = array('success' => false, 'messages' => array());

        $crm = $_POST['crm'];
        $package_ref = $_POST['package_ref'];
        $hostname = $_POST['hostname'];

        $sql = "INSERT INTO hosts (crm, package_ref, hostname) VALUES ('$crm', '$package_ref', '$hostname')";
        $query = $connect->query($sql);

        if($query === TRUE) {
                $validator['success'] = true;
                $validator['messages'] = "Successfully Added";
        } else {
                $validator['success'] = false;
                $validator['messages'] = "Error while adding the host information";
        }

        // close the database connection
        $connect->close();

        echo json_encode($validator);

}

javascript

var manageHostTable;

$(document).ready(function() {
        manageHostTable = $("#manageHostTable").DataTable({
                "ajax": "php_action/retrieve.php",
                "order": [],
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "oSearch": {"sSearch": $.urlParam('search') }
        });

        $("#addHostModalBtn").on('click', function() {
                // reset the form
                $("#createHostForm")[0].reset();
                // remove the error
                $(".form-group").removeClass('has-error').removeClass('has-success');
                $(".text-danger").remove();
                // empty the message div
                $(".messages").html("");

                // submit form
                $("#createHostForm").unbind('submit').bind('submit', function() {

                        $(".text-danger").remove();

                        var form = $(this);

                        // validation
                        var crm = $("#crm").val();
                        var package_ref = $("#package_ref").val();
                        var hostname = $("#hostname").val();

                        if(crm == "") {
                                $("#crm").closest('.form-group').addClass('has-error');
                                $("#crm").after('<p class="text-danger">The CRM field is required</p>');
                        } else {
                                $("#crm").closest('.form-group').removeClass('has-error');
                                $("#crm").closest('.form-group').addClass('has-success');
                        }
                        if(package_ref == "") {
                                $("#package_ref").closest('.form-group').addClass('has-error');
                                $("#package_ref").after('<p class="text-danger">The Package Reference field is required</p>');
                        } else {
                                $("#package_ref").closest('.form-group').removeClass('has-error');
                                $("#package_ref").closest('.form-group').addClass('has-success');
                        }

                        if(hostname == "") {
                                $("#hostname").closest('.form-group').addClass('has-error');
                                $("#hostname").after('<p class="text-danger">The Hostname field is required</p>');
                        } else {
                                $("#hostname").closest('.form-group').removeClass('has-error');
                                $("#hostname").closest('.form-group').addClass('has-success');
                        }

                        if(crm && package_ref && hostname ) {
                                //submit the form to server
                                $.ajax({
                                        url : form.attr('action'),
                                        type : form.attr('method'),
                                        data : form.serialize(),
                                        dataType : 'json',
                                        success:function(response) {

                                                // remove the error
                                                $(".form-group").removeClass('has-error').removeClass('has-success');
                                                if(response.success == true) {
                                                        $(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                                                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                                                          '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                                                        '</div>');

                                                        // reset the form
                                                        $("#createHostForm")[0].reset();

                                                        // reload the datatables
                                                        manageHostTable.ajax.reload(null, false);
                                                        // this function is built in function of datatables;

                                                } else {
                                                        $(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                                                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                                                          '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                                                        '</div>');
                                                }  // /else
                                        } // success
                                }); // ajax subit
                        } /// if


                        return false;
                }); // /submit form for create host
        }); // /add modal

});

发现我的问题。我没有为每个 select 提供 name

之前

<select class="form-control form-control-md" id="crm">

之后

<select class="form-control form-control-md" name="crm" id="crm">