【发布时间】:2016-12-15 15:54:03
【问题描述】:
我试图在从 Mysql 数据库中删除作者之前向用户显示确认是/否提示。当用户在 authors.html.php 中点击 Delete 时,控制器会包含一个 confirm.php。 confirm.php 提示用户输入是或否来确认。如果单击 yes 按钮,confirm.php 会将 id 传递回控制器,然后控制器检查是否设置了 action,如果是,则根据 id 删除作者。
不幸的是,作者没有被删除,所以问题在于包含确认提示。如果没有确认包含,脚本可以很好地工作,但我想弄清楚出了什么问题,而且使用 Javascript 太容易了。
任何帮助表示赞赏。
我的控制器:index.php
//inlcude the data connection.
include $_SERVER['DOCUMENT_ROOT'] . '/authors/includes/db.inc.php';
try
{
$result = $pdo->query('SELECT id, name FROM author'); //Rows of a result set returned by fetch are represented as associative arrays,
}
catch (PDOException $e)
{
$error = 'Error fetching authors from the database!';
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php';
if(isset($_POST['action']) and $_POST['action'] == 'Delete') {
include "confirm.php";
if(isset($_POST['action']) and $_POST['action'] == 'Yes') {
try {
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo -> prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e) {
$error = "Error deleting author.";
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}// if yes
} // end if isset delete
authors.html.php 然后显示作者列表:
<?php foreach ($authors as $author): ?><!-- loop through the list of authors pulled from the database by the controller -->
<li>
<form action="" method="post">
<div>
<?php htmlout($author['name']); ?> <!--display a list of authors and an edit and delete button-->
<input type="hidden" name="id" value="<?php
echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</li>
<?php endforeach; ?>
确认.php ......
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $author['id']; ?>">
<input type="submit" name="action" value="Yes">
<!--input type="submit" name="action" value="No"-->
</form>
【问题讨论】:
-
您的确认表格有误。它应该是
$_POST['id'],因此您捕获选择删除的作者的 ID,NOT$author['id'],这是作者列表中输出的最后一个作者。 -
嗯,我真的不明白这是如何工作的......您知道您只能在浏览器中显示的页面的完全重新加载中包含这样的确认脚本的PHP?这听起来很不直观。如果必须在步骤之间咨询服务器,那么基于纯客户端逻辑 (javascript) 或 ajax 调用(也基于 javascript)实现确认步骤不是更有意义吗?
-
马克B,把隐藏字段的值改成$_POST['id']还是不行。
-
arkascha,是的,我在帖子中明确表示 JS 或 Ajax 可以解决问题,但我仍然想从纯粹的学习角度找出问题所在。我已经看到你因为提出问题和学习的愿望而受到惩罚 - 无法取胜
-
您尝试过吗:
$sql='DELETE FROM author WHERE id ='.$_POST[id]或$sql="DELETE FROM author WHERE id = $_POST[id]"。我认为您的意思是$_POST[id]而不是id。如果您在 php 中使用单引号中的变量名,它们将不会被解释为变量。所以我使用.运算符将变量与字符串连接起来。其他选项可能是使用解释变量的双引号(不确定作为查询传递时双引号是否有效)。只是一个建议。不过不确定。 “如果我错了,请有人纠正我。拜托!”