php - 使用 SQL 的删除按钮无法正常工作
问题描述
我正在做一个唱片项目,但我遇到了一个问题,即“删除选择”按钮没有删除该行。到目前为止,我与数据库的连接正常,它正确地回显了信息,但实际上并没有从数据库中删除该行。我目前正在使用 MySQLi。
这是完整的代码:
<?php
include '../includes/connection.php';
//Include from admin folder
include './includes/login.php';
login();
// initialize flags
$OK = false;
$deleted = false;
$stmt = $conn->stmt_init();
if (isset($_GET['id']) && !$_POST) {
// prepare SQL query
$sql = 'SELECT id, album_name FROM album2img WHERE id = ?';
if ($stmt->prepare($sql)) {
// bind the query parameters
$stmt->bind_param('i', $_GET['id']);
// execute the query, and fetch the result
$OK = $stmt->execute();
// bind the result to variables
$stmt->bind_result($id, $album_name);
$stmt->fetch();
}
}
if (isset($_POST['delete'])) {
$sql = 'DELETE FROM album2img WHERE id = ?';
if ($stmt->prepare($sql)) {
$stmt->bind_param('i', $_POST['id']);
$stmt->execute();
// if there's an error affected_rows is -1
if ($stmt->affected_rows > 0) {
$deleted = true;
} else {
$error = 'There was a problem deleting the record.';
}
}
}
if ($deleted || isset($_POST['cancel']) || !isset($_GET['id'])) {
header('Location: http://localhost/3rdquarterproject/admin/album_list.php');
exit;
}
// if any SQL query fails, get the error message
if (isset($stmt) && !$OK && !$deleted) {
$error .= $stmt->error;
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Delete Album</title>
</head>
<body>
<h1>Delete Album</h1>
<?php
if (isset($error) && !empty($error)) {
echo "<p>Error: $error</p>";
}
if($id == 0) { ?>
<p>Invalid request: record does not exist.</p>
<?php } else { ?>
<p>Please confirm that you want to delete the following item. This action cannot be undone.</p>
<p><?php echo $id; echo ". "; echo $album_name; ?></p>
<?php } ?>
<form method="post" action="album_delete.php">
<p>
<?php if(isset($id) && $id > 0) { ?>
<input type="submit" name="delete" value="Confirm Deletion">
<?php } ?>
<input name="cancel" type="submit" value="Cancel">
<?php if(isset($id) && $id > 0) { ?>
<input name="album_name" type="hidden" value="<?= $album_name; ?>">
<?php } ?>
</p>
</form>
</body>
</html>
我不确定我是否在删除部分正确使用了准备好的语句:
if (isset($_POST['delete'])) {
$sql = 'DELETE FROM album2img WHERE id = ?';
if ($stmt->prepare($sql)) {
$stmt->bind_param('i', $_POST['id']);
$stmt->execute();
// if there's an error affected_rows is -1
if ($stmt->affected_rows > 0) {
$deleted = true;
} else {
$error = 'There was a problem deleting the record.';
}
}
}
我还是很新,所以期待大家的回应!
解决方案
推荐阅读
- java - 为什么我的 Spring Batch 多线程步骤在任何处理之前执行所有读取?
- excel - 将编码放入 ListObject 表中
- javascript - nodejs + express 从数据库加载上下文配置
- javascript - 将对象的每个道具转换为对象数组
- java - 如何检查 Java 是否使用配置的代理服务器?
- javascript - 使用 NodeJS 更改 HTML 显示的文本
- javascript - 当我使用 javascript 加载图像时,$_FILES 为空
- javascript - html2canvas 未捕获日期选择器
- python - 两个数据应该使用 python 在 csv 中输出唯一值
- r - R命令系统的含义(“触摸AAA”)