无法将插入的值保存到 tableview 和 mySQL - PHP

Posted

技术标签:

【中文标题】无法将插入的值保存到 tableview 和 mySQL - PHP【英文标题】:Unable to save inserted value into tableview and mySQL - PHP 【发布时间】:2018-12-08 16:45:46 【问题描述】:

我想将新项目添加到表中,同时将它们插入数据库 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"  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;


?>

【问题讨论】:

我认为这是您的部分代码,请提供更多信息。您已经编写了 PHP 函数,但它们是如何调用的? 感谢您的陈述,我已经提供了我的完整代码。我希望它很清楚。 提供完整代码会降低我们对线程的关注。请考虑在您的问题中仅包含代码的相关部分。 【参考方案1】:

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

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

然后,在修复该问题后,我只能插入一行。这仅仅是因为我没有在数据库 mySQL 中为列 'id' 查询 'AUTO_INCREMENT'。无论如何,谢谢先生回答我的问题,我是新手。

【讨论】:

以上是关于无法将插入的值保存到 tableview 和 mySQL - PHP的主要内容,如果未能解决你的问题,请参考以下文章

将tableview中的所有值保存到iOS中的数组?

快速将uiimageview保存到tableview?

无法将值插入 tableview - JavaFx

无法将录制的文件列出到 TableView

无法将“Int”类型的值分配给“String”类型?在 (cellForRowAt) 中使用 Tableview

SQL语法错误:无法将 NULL值插入列'',该列不允许空值。INSERT失败。怎么解决啊