我能够在我的数据库表中插入数据并查看所有内容,但是现在我尝试使删除按钮工作,我刷新了页面并在删除时看到了未定义的索引。
表格如下:
<?php
foreach ($rows as $row){ ?>
<div>
<h3><?php echo $row['title']; ?></h3>
<p><?php echo $row['body']; ?></p>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
<input type="submit" name="delete" value="Delete">
</form>
</div>
<?php }
?>
然后在下面的代码中我想简单地回显ID,但它不起作用:
if($_POST['delete']){
echo $_POST['delete_id'];
}
这是我的完整代码,以防你需要了解更多信息:
<?php
require 'classes/Database.php';
$database = new Database;
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($_POST['delete']){
echo $_POST['delete_id'];
}
if($post['submit']){
$id = $post['id'];
$title = $post['title'];
$body = $post['body'];
$database->query('UPDATE posts SET title = :title, body = :body WHERE id = :id');
$database->bind(':title', $title);
$database->bind(':body', $body);
$database->bind(':id', $id);
$database->execute();
if($database->lastInsertId()){
echo '<p>Post added</p>';
}
}
$database->query('SELECT * FROM posts');
$rows = $database->resultSet();
?>
<h1>Add Posts</h1>
<!-- Our action is/can be the page that we are on -->
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<label for="">Post ID</label><br />
<input type="text" name="id" placeholder="Specify the ID..."><br /><br />
<label for="">Add title</label><br />
<input type="text" name="title" placeholder="Add a title..."><br />
<label>Post body</label><br />
<textarea name="body"></textarea><br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<h1>Posts</h1>
<div>
<?php
foreach ($rows as $row){ ?>
<div>
<h3><?php echo $row['title']; ?></h3>
<p><?php echo $row['body']; ?></p>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
<input type="submit" name="delete" value="Delete">
</form>
</div>
<?php }
?>
</div>
如何进行删除工作?
答案 0 :(得分:4)
只需使用isset检查数组中是否存在具有指定键的元素:
if(isset($_POST['delete'])) {
echo isset($_POST['delete_id']) ? $_POST['delete_id'] : 'something else';
}
但最好的方式是这样的:
<?php
$fields = ['delete', 'delete_id', 'post', 'body', 'title']; //every field you need
$errors = [];
foreach ($fields as $field) {
if (!isset($_POST[$field]) {
$errors[] = 'Please, fill field with name '.$field
}
}
if ($errors) {
//display errors...
}
答案 1 :(得分:1)
如果您启用了默认错误报告,则需要更改if语句:
if($_POST['delete']){
echo $_POST['delete_id'];
}
为:
if(isset($_POST['delete']) && isset($_POST['deleted_id'])){
echo $_POST['delete_id'];
}
目前,如果您刷新页面(而不是发布),它将抛出未定义的索引通知。这是因为如果刷新页面,则表示您正在执行GET请求而不存在POST数据,因此未定义$ _POST ['delete_id']。
如果您点击“删除”按钮,表单将使用POST请求提交,重新加载的页面将会消失。
如果错误仍然存在,请确保$ row ['id']具有值。
此外,您还需要在测试中添加isset:
if($post['submit']){
这样就变成了:
if(isset($post['submit'])){
这与上述原因相同。