将数据添加到Datatable - PHP POST会话,Bootstrap Modal,MySQL和 AJAX

ru9i0ody  于 2023-05-16  发布在  PHP
关注(0)|答案(1)|浏览(110)

我已经花了三个月的时间才想出办法。
我有一个管理员帐户谁可以添加设备到每个用户/s,我使用Datatable显示和操纵每个用户的设备列表。
MySQL数据库表如下:
表名称:admin表列:[ID] [用户名] [密码]
表名称:device表列:[id] [uid] [product_name] [description] [serial_number] [date_delivered] [warranty_expiration] [dr_number] [reports] [reported_data] [replaced_unit_serial_number] [replacement_data] [remarks]
表名称:user表列:[id] [fname] [lname] [email] [password] [contactno] [posting_date]
如上所述,表device [uid]与表user [id]有关系,因此将在用户配置文件中显示的设备列表是唯一的。
密码来了。。
user-profile.php

<?php 
ob_start();
session_start();
include_once('../includes/config.php');

if (!strlen($_SESSION['adminid']==0)) {
  header('location:logout.php');
  } else{
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>User Profile | Registration and Login System</title>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
        <link href="../css/styles.css" rel="stylesheet" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap.min.js"></script>
        <script src="js/data.js"></script>  
       
    </head>
    <body class="sb-nav-fixed">
      <?php include_once('includes/navbar.php');?>
        <div id="layoutSidenav">
          <?php include_once('includes/sidebar.php');?>
            <div id="layoutSidenav_content">
                <main>
                    <div class="container-fluid px-4">
                   <div class="row d-flex justify-content-between align-items-center">
                            <div class="col-lg-12">        
                                <div class="panel-heading">
                                    <div class="row">
                                        <div class="col-md-10">
                                            <h3 class="panel-title">Registered Devices</h3>
                                        </div>
                                        <div class="col-md-2" align="right">
                                            <button type="button" name="add" id="addDevice" class="btn btn-success btn-xs">Add New Device</button>
                                        </div>
                                    </div>
                                </div>
                                <table id="devicesList" class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Product Name</th>
                                            <th>Description</th>                    
                                            <th>Serial Number</th>
                                            <th>Date Delivered</th>
                                            <th>Warranty Expiration</th> 
                                            <th>DR Number</th>  
                                            <th>Reports</th>
                                            <th>Reported Data</th>
                                            <th>Replaced Unit Serial Number</th>
                                            <th>Replacement Data</th>
                                            <th>Remarks</th>                            
                                            <th></th>
                                            <th></th>                   
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                            <div class="modal fade" id="devicesModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                    <form method="post" id="devicesForm" name="devicesForm">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close" data-bs-dismiss="modal">&times;</button>
                                                <h4 class="modal-title"><i class="fa fa-plus"></i> Edit Device</h4>
                                            </div>
                                            <div class="modal-body">
                                                <div class="form-group">
                                                    <label for="product_name" class="control-label">Product Name</label>
                                                    <input type="text" class="form-control" id="product_name" name="product_name" placeholder="Product Name">            
                                                </div>
                                                <div class="form-group">
                                                    <label for="description" class="control-label">Description</label>
                                                    <input type="text" class="form-control" id="description" name="description" placeholder="Description">            
                                                </div>
                                                <div class="form-group">
                                                    <label for="serial_number" class="control-label">Serial Number</label>
                                                    <input type="text" class="form-control" id="serial_number" name="serial_number" placeholder="Serial Number">            
                                                </div>
                                                <div class="form-group">
                                                    <label for="date_delivered" class="control-label">Date Delivered</label>
                                                    <input type="date" class="form-control" id="date_delivered" name="date_delivered" placeholder="Date Delivered">            
                                                </div>
                                                <div class="form-group">
                                                    <label for="warranty_expiration" class="control-label">Warranty Expiration</label>
                                                    <input type="date" class="form-control" id="warranty_expiration" name="warranty_expiration" placeholder="Warranty Expiration">            
                                                </div><div class="form-group">
                                                    <label for="dr_number" class="control-label">DR Number</label>
                                                    <input type="text" class="form-control" id="dr_number" name="dr_number" placeholder="DR Number">
                                                </div>
                                                <div class="form-group">
                                                    <label for="reports" class="control-label">Reports</label>
                                                    <input type="text" class="form-control" id="reports" name="reports" placeholder="Reports" required>
                                                </div>
                                                <div class="form-group">
                                                    <label for="reported_data" class="control-label">Reported Data</label>
                                                    <input type="text" class="form-control" id="reported_data" name="reported_data" placeholder="Reported Data">
                                                </div> 
                                                <div class="form-group">
                                                    <label for="replaced_unit_serial_number" class="control-label">Replaced Unit Serial Number</label>
                                                    <input type="text" class="form-control" id="replaced_unit_serial_number" name="replaced_unit_serial_number" placeholder="Reported Data">
                                                </div> 
                                                <div class="form-group">
                                                    <label for="replacement_data" class="control-label">Replacement Data</label>
                                                    <input type="text" class="form-control" id="replacement_data" name="replacement_data" placeholder="Replacement Data">
                                                </div> 
                                                <div class="form-group">
                                                    <label for="remarks" class="control-label">Remarks</label>
                                                    <input type="text" class="form-control" id="remarks" name="remarks" placeholder="Remarks">
                                                </div> 
                                                                  
                                            </div>
                                            <div class="modal-footer">
                                                <?php
                                                    if (isset($_GET['id'])) {
                                                        $id = $_GET['id'];
                                                        echo '<input type="hidden" name="empId" id="empId" value="' .$id. '" />';
                                                    } else {
                                                        echo '<input type="hidden" name="empId" id="empId" />';
                                                    }
                                                ?>
                                                 <?php
                                                    if(isset($_GET['uid'])) {

                                                    $userid = $_GET['uid'];
                                                    echo '<input type="hidden" name="userId" id="userId" value="' .$userid. '" />';
                                                    } else {
                                                        echo '<input type="hidden" name="userId" id="userId"/>';
                                                    }
                                                    
                                                ?>
                                                <input type="hidden" name="action" id="action" value="" />
                                                <input type="submit" name="submit" id="submit" class="btn btn-info" />
                                                <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            

                        </div>
                    </div>
                </main>
          <?php include('../includes/footer.php');?>
            </div>
        </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.1/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
        <!-- <script src="js/modify_records.js"></script> -->
        <script src="../js/scripts.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
        <script src="../js/datatables-simple-demo.js"></script>

这是显示设备列表的位置。
devices.php

<?php
require('includes/config.php');

class Devices extends Dbconfig {
    protected $hostName;
    protected $userName;
    protected $password;
    protected $dbName;
    private $empTable = 'device';
    private $dbConnect = false;
    public function __construct(){
        if(!$this->dbConnect){      
            $database = new dbConfig();            
            $this -> hostName = $database -> serverName;
            $this -> userName = $database -> userName;
            $this -> password = $database ->password;
            $this -> dbName = $database -> dbName;          
            $conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
 
            if($conn->connect_error){
                die("Error failed to connect to MySQL: " . $conn->connect_error);
            } else{
                $this->dbConnect = $conn;
            }

        }
    }

    public function addDevice(){

        global $database;

            $insertQuery = "INSERT INTO ".$this->empTable." (uid, product_name, description, serial_number, date_delivered, warranty_expiration, dr_number, reports, reported_data, replaced_unit_serial_number, replacement_data, remarks) 
                VALUES ('".$_POST["userId"]."', '".$_POST["product_name"]."', '".$_POST["description"]."', '".$_POST["serial_number"]."', '".$_POST["date_delivered"]."', '".$_POST["warranty_expiration"]."', '".$_POST["dr_number"]."', '".$_POST["reports"]."', '".$_POST["reported_data"]."', '".$_POST["replaced_unit_serial_number"]."' , '".$_POST["replacement_data"]."', '".$_POST["remarks"]."')";
            $isUpdated = mysqli_query($this->dbConnect, $insertQuery);  

            if($isUpdated == true) {
                echo "Data was inserted successfully!";
            }
            else {
                echo "Error: " . $sql . "<br>" . mysqli_error($database);
            }
    }
}

?>

data.js

$(document).ready(function(){
    var userId = $('#userId').val();
    var devicesData = $('#devicesList').DataTable({
        "lengthChange": false,
        "searching": false,
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"action.php",
            type:"POST",
            data: {
                userId : userId, 
                action:'listDevices'
            },
            dataType:"json"
        },
        "columnDefs":[
            {
                "targets":[0, 6, 7],
                "orderable":true,
            },
        ],
        "pageLength": 10
    });

$("#devicesModal").on('submit','#devicesForm', function(event){
        event.preventDefault();
        var userId = $('#userId').val();
        var formData = $(this).serialize();
        $('#submit').attr('disabled','disabled');
        $.ajax({
            url:"action.php",
            method:"POST",
            data: { userId:userId, action:formData },
            success:function(data){

                    $('#devicesForm')[0].reset();
                    $('#devicesModal').modal('hide');               
                    $('#submit').attr('disabled', false);
                    devicesData.clear();
                    devicesData.rows.add(data);
                    devicesData.draw();

            },
            error: function(jqXHR, textStatus){
                alert("Status: "+ jqXHR.status);
                alert("textStatus "+ textStatus);
            }
        });

    });     

     

});

action.php

<?php 
require('devices.php');
//include_once('/includes/config.php');

$emp = new Devices();
if(!empty($_POST['action']) && $_POST['action'] == 'listDevices') {
    $emp->devicesList();
}
    
if(!empty($_POST['action']) && $_POST['action'] == 'addDevice') {
    $emp->addDevice();
}

?>

到目前为止,我可以在payload中打印json输出:
userId:13 action:product_name=test&description=test&serial_number=testt&date_delivered= 2023 -05-02&warranty_expiration=2023-05-30&dr_number=tes&reports=test&reported_data=test&replaced_unit_serial_number=test&replacement_data=test&remarks=test&empId=&userId=13&action=addEmployee
但是我不知道如何在Datatable中实现这一点。

ve7v8dk2

ve7v8dk21#

你的代码有一些变化。正如我所看到的,你在问题中提到的代码不能插入数据库。你必须按如下方式修改你的代码。

第一步

data: { userId:userId, action:formData },更改为data: { userId:userId, action:'addDevice', pData : formData },
通过这样做,action.php中的第二个条件将匹配并尝试执行$emp->addDevice();

第二步

devices.php中完全更改方法addDevices(),如下所示。

public function addDevice(){
    // global $database; <-- Why this var? you are using no where here.

    // Prepare the statement securely.
    $insertQuery = "INSERT INTO ".$this->empTable." (uid, product_name, description, serial_number, date_delivered, warranty_expiration, dr_number, reports, reported_data, replaced_unit_serial_number, replacement_data, remarks) 
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";

    $statement = mysqli_prepare($this->dbConnect, $insertQuery);

    // Now, bind all the post data to each placeholders given above.
    mysqli_stmt_bind_param($statement, "issississsss", $_POST['pData']["userId"],$_POST['pData']["product_name"],$_POST['pData']["description"],$_POST['pData']["serial_number"],$_POST['pData']["date_delivered"],$_POST['pData']["warranty_expiration"],$_POST['pData']["dr_number"],$_POST['pData']["reports"],$_POST['pData']["reported_data"],$_POST['pData']["replaced_unit_serial_number"],$_POST['pData']["replacement_data"],$_POST['pData']["remarks"]);
    
    // Execute the statement prepared with data.
    mysqli_stmt_execute($statement); 

    // Get number of rows affected because of above insert statement.
    $rows = mysqli_stmt_affected_rows($statement);

    // If $rows is more than 0, then the statement executed successfully.
    if($rows > 0) {
         echo "Data was inserted successfully!";
    }
    else 
    {
         echo "Error: " . $sql . "<br>" . mysqli_error($database);
    }
}

通过绑定参数,您的数据将安全地插入到数据库中。

忠告:-不转义、不绑定,请勿插入、更新数据。

相关问题