【发布时间】:2021-04-09 01:14:37
【问题描述】:
我想使用 jQuery 从数据库中删除行。 我已经使用 PHP 检索了数据库表,并希望在单击删除按钮时从数据库中删除该行。
这是我的代码。 adm_complaints.php
<?php include('register.php') ?>
<!DOCTYPE html>
<html>
<head><title>AMC Hostel</title>
</head>
<body>
<table id="t02">
<tr class="header">
<th>Student name</th>
<th>Complaint</th>
<th>Date of complaint</th>
<th></th>
</tr>
<tbody>
<?php
$sql="select student_name, complaint, date_of_complaint from complaints";
$result = $conn->query($sql);
?>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row" class="complaints_row">
<td class="name"><?php echo $row['student_name']; ?></td>
<td><?php echo $row['complaint']; ?></td>
<td><?php echo $row['date_of_complaint']; ?></td>
<td><button class="show-name">Delete</button></td>
</tr>
<?php } ?>
</table>
<script>
$(".show-name").click(function(){
var $row = $(this).closest("tr");
var $text = $row.find('.name').text();
$.ajax({
url : "delete.php",
success: function(data){
alert('Directory created');
}
});
});
</script>
在这里,我希望在单击删除按钮时从 MySQL 数据库中删除该行。 这是我的 delete.php
<?php
include 'adm_complaints.php';
$host="localhost";
$port=3306;
$socket="MySQL";
$user="root";
$password="";
$dbname="hostel_management";
$conn = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
$resolve="delete from complaints where student_name='$text'";
$resolved=mysqli_query($conn, $resolve) or die(mysqli_error($conn));;
?>
当我单击删除按钮时,警报框显示“已创建目录”,但该行并未在数据库中删除。 我是 JQuery 的新手,所以即使我犯了任何愚蠢的错误,也请告诉我。 提前致谢。
【问题讨论】:
-
你不能以这种方式在 PHP(服务器)中使用 JS(客户端)变量...多研究 AJAX。
-
你不需要 jQuery 来完成这么简单的任务 - 使用 vanilla JS:blog.garstasio.com/you-dont-need-jquery/ajax
-
在代码中使用
die(mysqli_error($conn));是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die?