只有删除选项不起作用PHP CRUD
我一直在研究基本的PHP CRUD。我正在使用基于只有删除选项不起作用PHP CRUD,php,jquery,mysql,ajax,crud,Php,Jquery,Mysql,Ajax,Crud,我一直在研究基本的PHP CRUD。我正在使用基于PHP、AJAX、MySQL的CRUD 我有像添加/更新/删除/获取结果/搜索这样的功能。除了删除选项外,一切正常。我尝试了很多方法来解决这个问题,但似乎无法在代码中找到确切的错误。下面是我用于CRUD操作的代码 exam_packages.php <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/htm
PHP、AJAX、MySQL
的CRUD
我有像添加/更新/删除/获取结果/搜索这样的功能。除了删除
选项外,一切正常。我尝试了很多方法来解决这个问题,但似乎无法在代码中找到确切的错误。下面是我用于CRUD操作的代码
exam_packages.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add / Update / Delete Exam Packages</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="all">
<link href="css/jquery.bootgrid.css" rel="stylesheet" />
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1 style="text-align: center;">Add / Update / Delete Exam Packages</h1>
<div class="col-sm-12">
<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 New Exam Package</button></div></div>
<table id="exam_package_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="pkg_id" data-type="numeric" data-identifier="true">Package ID</th>
<th data-column-id="test_quantity">Test Quantity</th>
<th data-column-id="price">Price</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">×</button>
<h4 class="modal-title">Add New Exam Package</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="test_quantity" class="control-label">Test Quantity:</label>
<input type="text" class="form-control" id="test_quantity" name="test_quantity"/>
</div>
<div class="form-group">
<label for="price" class="control-label">Price:</label>
<input type="text" class="form-control" id="price" name="price"/>
</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>
<div id="edit_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">×</button>
<h4 class="modal-title">Edit Exam Package</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_pkg_id" id="edit_pkg_id">
<div class="form-group">
<label for="test_quantity" class="control-label">Test Quantity:</label>
<input type="text" class="form-control" id="edit_test_quantity" name="edit_test_quantity"/>
</div>
<div class="form-group">
<label for="price" class="control-label">Price:</label>
<input type="text" class="form-control" id="edit_price" name="edit_price"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#exam_package_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "exam_package_response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.pkg_id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.pkg_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_pkg_id = $(this).parent().siblings(':first').html();
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_pkg_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_test_quantity').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_price').val(ele.siblings(':nth-of-type(3)').html());
} else {
alert('No row selected! First select row, then click edit button');
}
}).end().find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete No.' + $(this).data("row-id") + ' package?');
alert(conf);
if(conf==true){
// console.log($(this).data("row-id"));
$.post('exam_package_response.php', { id: $(this).data("row-id"), action:'delete'}, function()
{
$("#exam_package_grid").bootgrid('reload');
});
$(this).parent('tr').remove();
$("#exam_package_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "exam_package_response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#exam_package_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
});
</script>
添加/更新/删除考试包
添加/更新/删除考试包
添加新的考试包
包ID
试验量
价格
命令
&时代;
添加新的考试包
测试数量:
价格:
接近
拯救
&时代;
编辑考试包
测试数量:
价格:
接近
拯救
$(文档).ready(函数(){
var grid=$(“#考试#包_grid”).bootgrid({
阿贾克斯:没错,
rowSelect:true,
职位:职能()
{
/*使用请求对象累积自定义参数的步骤*/
返回{
id:“b0df282a-0d67-40e5-8558-c9e93b7befed”
};
},
url:“exam\u package\u response.php”,
格式化程序:{
“命令”:功能(列、行)
{
返回“”+
"";
}
}
}).on(“loaded.rs.jquery.bootgrid”,函数()
{
/*在加载和呈现数据后执行*/
grid.find(“.command edit”)。在(“单击”上,函数(e)
{
//警报(“您按了行上的编辑:”+$(this).data(“行id”);
var ele=$(this.parent();
var g_pkg_id=$(this.parent().sides(':first').html();
//console.log(grid.data())//
$('edit#u model').model('show');
如果($(this).data(“行id”)>0){
//收集数据
$('#edit_pkg_id').val(ele.sibbins(':first').html());//以防更改密钥
$('#edit_test_quantity').val(元素同级(':n类型(2)').html());
$('edit#u price').val(ele.sibbins('n:nth of type(3)').html());
}否则{
警报(“未选择行!首先选择行,然后单击编辑按钮”);
}
}).end().find(“.command delete”)。在(“单击”上,函数(e)
{
var conf=confirm('Delete No.+$(this).data(“row id”)+'package?');
警报(形态);
如果(conf==true){
//log($(this.data(“行id”));
$.post('exam\u package\u response.php',{id:$(this).data(“row id”),action:'delete'},function()
{
$(“#检查#包#网格”).bootgrid('reload');
});
$(this.parent('tr').remove();
$(“#考试#软件包_网格”).bootgrid('remove',$(this).data(“行id”))
}
});
});
函数ajaxAction(action){
数据=$(“#frm#”+操作).serializeArray();
$.ajax({
类型:“POST”,
url:“exam\u package\u response.php”,
数据:数据,
数据类型:“json”,
成功:功能(响应)
{
$(“#”+动作+“#模型”).modal('hide');
$(“#检查#包#网格”).bootgrid('reload');
}
});
}
$(“#命令添加”)。单击(函数(){
$('add#u model').model('show');
});
$(“#btn_添加”)。单击(函数(){
ajaxAction(“添加”);
});
$(“#btn_编辑”)。单击(函数(){
ajaxAction(“编辑”);
});
});
test\u package\u response.php
<?php
//include connection file
include_once("db_connection_mysqli.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
// console.log($params);
// echo '<script>alert("aaaaaaaaaa");</script>';
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new ExamPackage($connString);
switch($action) {
case 'add':
$empCls->insertExamPackage($params);
break;
case 'edit':
$empCls->updateExamPackage($params);
break;
case 'delete':
$empCls->deleteExamPackage($params);
break;
default:
$empCls->getExamPackages($params);
return;
}
class ExamPackage {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getExamPackages($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertExamPackage($params) {
$data = array();;
$sql = "INSERT INTO `tblExamPackages` (test_quantity, price) VALUES('" . $params["test_quantity"] . "', '" . $params["price"] . "'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert package 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 .=" (test_quantity LIKE '%".$params['searchPhrase']."%' ";
$where .=" OR price = '".$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 `tblExamPackages` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot package data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch package data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateExamPackage($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `tblExamPackages` set test_quantity = '" . $params["edit_test_quantity"] . "', price='" . $params["edit_price"]."' WHERE pkg_id='".$_POST["edit_pkg_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update package data");
}
function deleteExamPackage($params) {
$data = array();
echo "<script>
var conf = confirm('Delete No.' + $(this).data('row-id') + ' package?');
alert(conf);</script>";
$sql = "delete from `tblExamPackages` WHERE pkg_id'" . $_REQUEST["edit_pkg_id"] . "'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete package data");
}
}
?>
简短回答:
您的删除查询有语法错误。评论中暗示了这一点
通过尝试在php类中使用JavaScript,您还混合了服务器端和客户端。这是一个重大错误,需要一些人回顾一下基础知识
长答覆:
我感觉到你正试图朝着面向对象编程的方向发展,而且你做的一些事情是正确的;值得注意的是,将数据库连接注入到crud对象中
但有些事情可以做得更好。这里有一些想法-
不要使用mysqli,而是使用预先准备好的语句。这很可能消除了查询中的语法错误
始终从Ajax请求返回json编码的数据。我个人总是让php脚本响应类似于returnJSON_encode(['message'=>$message,'data'=>$data])代码>。然后,浏览器中的JavaScript可以决定与用户通信的内容
方法应该做一件事。如果方法变得比屏幕上适合的更大,您可能需要重构。例如,getRecords()
检查页码,创建查询,获取总数,并获取所有记录。这个
`$sql = "delete from `tblExamPackages` WHERE pkg_id'" . $_REQUEST["edit_pkg_id"] . "'";`
$sql = `"delete from `tblExamPackages` WHERE pkg_id = '" . $_REQUEST["edit_pkg_id"] . "'";`
function createCookie(name, value, days)
{
var expires;
if (days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else
{
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
createCookie("pkg_id", $(this).data("row-id"), "1");
$pkg_id = $_COOKIE["pkg_id"];