php - 无法将插入的值保存到 TableView 和 mySQL 中 - PHP

标签 php html mysql insert save

我想将新项目添加到表中,同时将它们插入到数据库 mySQL 中。但是,当我单击“保存”时,它不会执行任何操作,也不会显示任何错误。我不知道哪一部分是错误的。

我的 html n js 代码

<?php
include_once ("connect.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Item List</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" 
media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>

</head>
<body>

<div class="container">
  <div class="">
    <h1>Needed Item List</h1>
    <div class="col-sm-8">
    <div class="well clearfix">
        <div class="pull-right"><button type="button" class="btn btn-xs 
btn-primary" id="command-add" data-row-id="0">
        <span class="glyphicon glyphicon-plus"></span> Add Item</button> 
</div></div>
    <table id="item_grid" class="table table-condensed table-hover table- 
striped" width="60%" cellspacing="0" data-toggle="bootgrid">
        <thead>
            <tr>
                <th data-column-id="id" data-type="numeric" data- 
identifier="true">No</th>
                <th data-column-id="itemCat">Item Category</th>
                <th data-column-id="itemName">Item Name</th>
                <th data-column-id="quantity">Quantity</th>
                <th data-column-id="commands" data-formatter="commands" 
data-sortable="false">Commands</th>
            </tr>
        </thead>
    </table>
</div>
  </div>
</div>

<div id="add_model" class="modal fade">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria- 
hidden="true">&times;</button>
            <h4 class="modal-title">Add Item</h4>
        </div>
        <div class="modal-body">
        <form method="post" id="frm_add">
            <input type="hidden" value="add" name="action" id="action">
              <div class="form-group">
                <label for="name" class="control-label">Item Name:</label>
                <input type="text" class="form-control" id="name" 
name="name"/>
              </div>
              <div class="form-group">
                <label for="category" class="control-label">Item Category: 
</label>
                <input type="text" class="form-control" id="category" 
name="category"/>
              </div>
              <div class="form-group">
                <label for="quantity" class="control-label">Quantity: 
</label>
                <input type="text" class="form-control" id="quantity" 
name="quantity"/>
              </div>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default"data- 
dismiss="modal">Close</button>
            <button type="button" id="btn_add" class="btn btn- 
primary">Save</button>
        </div>
        </form>
    </div>
</div>
</div>

</body>
</html>
<script type="text/javascript">
 $( document ).ready(function() {
 var grid = $("#item_grid").bootgrid({
    ajax: true,
    rowSelect: true,
    post: function ()
    {
        /* To accumulate custom parameter with the request object */
        return {
            id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
        };
    },

    url: "action.php",
    formatters: {
            "commands": function(column, row)
            {
                return "<button type=\"button\" class=\"btn btn-xs btn- 
default command-edit\" data-row-id=\"" + row.id + "\"><span 
class=\"glyphicon 
glyphicon-edit\"></span></button> " + 
                    "<button type=\"button\" class=\"btn btn-xs btn- 
default command-delete\" data-row-id=\"" + row.id + "\"><span 
class=\"glyphicon glyphicon-trash\"></span></button>";
            }
        }
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
    //alert("You pressed edit on row: " + $(this).data("row-id"));
        var ele =$(this).parent();
        var g_id = $(this).parent().siblings(':first').html();
        var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
                console.log(g_name);

    //console.log(grid.data());//
    $('#edit_model').modal('show');
                if($(this).data("row-id") >0) {

                            // collect the data

$('#edit_id').val(ele.siblings(':first').html()); // in case we're 
changing the key
                            $('#edit_cat').val(ele.siblings(':nth-of- 
type(2)').html());
                            $('#edit_name').val(ele.siblings(':nth-of- 
type(3)').html());
                            $('#edit_quan').val(ele.siblings(':nth-of- 
type(4)').html());
                } else {
                 alert('Now row selected! First select row, then click 
edit button');
                }
}).end().find(".command-delete").on("click", function(e)
{

    var conf = confirm(' Are you sure you want to delete ID ' + 
$(this).data("row-id") + '?');
                //alert(conf);
                if(conf){
                            $.post('action.php', { id: $(this).data("row- 
id"), action:'delete'}
                                , function(){
// when ajax returns (callback), 
$("#item_grid").bootgrid('reload');
                            }); 
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', 
$(this).data("row-id"))
                }
});
});

function ajaxAction(action) {
            data = $("#frm_"+action).serializeArray();
            $.ajax({
              type: "POST",  
              url: "action.php",  
              data: data,
              dataType: "json",       
              success: function(response)  
              {
                $('#'+action+'_model').modal('hide');
                $("#item_grid").bootgrid('reload');
              }   
            });
        }

        $( "#command-add" ).click(function() {
          $('#add_model').modal('show');
        });
        $( "#btn_add" ).click(function() {
          ajaxAction('add');
        });
        $( "#btn_edit" ).click(function() {
          ajaxAction('edit');
        });
});
</script>

编辑、删除等其他部分没有问题。唯一的问题是添加新项目。无法插入数据库。

我的PHP代码

<?php
//include connection file 
include_once("connect.php");

$db = new dbObj();
$connString =  $db->getConnstring();

$params = $_REQUEST;

$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Item($connString);

switch($action) {
 case 'add':
    $empCls->insertItem($params);
 break;
 case 'edit':
    $empCls->updateItem($params);
 break;
 case 'delete':
    $empCls->deleteItem($params);
 break;
 default:
 $empCls->getItem($params);
 return;
}

class Item {
protected $conn;
protected $data = array();
function __construct($connString) {
    $this->conn = $connString;
}

public function getItem($params) {

    $this->data = $this->getRecords($params);

    echo json_encode($this->data);
}
function insertItem($params) {
    $data = array();
    $sql = "INSERT INTO `itemchecklist` (itemCat, itemName, quantity) 
VALUES('" . $params["category"] . "', '" . $params["name"] . "','" . 
$params["quantity"] . "');  ";

    echo $result = mysqli_query($this->conn, $sql) or die("error to insert 
item data");

}


function getRecords($params) {
    $rp = isset($params['rowCount']) ? $params['rowCount'] : 10;

    if (isset($params['current'])) { $page  = $params['current']; } else { 
$page=1; };  
    $start_from = ($page-1) * $rp;

    $sql = $sqlRec = $sqlTot = $where = '';


    if( !empty($params['searchPhrase']) ) {   
        $where .=" WHERE ";
        $where .=" ( itemCat LIKE '".$params['searchPhrase']."%' ";    
        $where .=" OR itemName LIKE '".$params['searchPhrase']."%' ";
        $where .=" OR quantity LIKE '".$params['searchPhrase']."%' )";

    }


   if( !empty($params['sort']) ) {  
        $where .=" ORDER By ".key($params['sort']) .' 
'.current($params['sort'])." ";
    }


   // getting total number records without any search
    $sql = "SELECT * FROM `itemchecklist` ";
    $sqlTot .= $sql;
    $sqlRec .= $sql;


?>

最佳答案

我已经知道问题出在哪里了。 首先,因为我没有在“添加”部分包含“id”参数

<input type="hidden" value="id" name="id" id="id">

然后,修复后我只能插入一行。这只是因为我没有在数据库 mySQL 中查询“id”列的“AUTO_INCRMENT”。不管怎样,谢谢先生回答我的问题,我是新手。

关于php - 无法将插入的值保存到 TableView 和 mySQL 中 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684691/

相关文章:

mysql - 如何在Python中获取此类JSON数据

php - MySql 限制和偏移给出错误结果

javascript - 使用ajax将数据发送到php页面并获取响应并显示在字段中

php - 如何使用 CSS 设置 PHP 回显结果的样式?

php - 将数据库项目添加到 php 表单

sockets - HTML5 Web 套接字接口(interface)如何工作?

html - 背景不显示

php - 非基本案例如何在递归中工作?

PHP显示join查询结果

javascript - 在 Html 中单击列表 (li) 项目不适用于 jquery