php - 无法在 PHP 中删除或更新行?

标签 php mysql mysqli

我正在开发我的第一个 PHP 应用程序,它是一个简单的笔记应用程序。 我对这样的笔记使用不同的 URL -

echo "<p><a href='/see_note.php?id={$row["note_id"]}'>{$row['note']}</a></p>";

因此,主键充当注释 URL 的参数。 该链接将我重定向到注释,没有任何问题,但是当我尝试删除或更新注释时,它会抛出此错误 -

Undefined index: ID in /home/user/PhpstormProjects/notes/see_note.php on line 17

第 17 行是我从 URL 中提取 id 的地方 -

$note_id = $_GET['id'];

这是显示注释的页面的其余代码-

//get id from the URL
$note_id = $_GET['id'];

//fetch the note from database
$query = "SELECT note from notes WHERE note_id = '$note_id'";
$query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
$row = mysqli_fetch_assoc($query_result);
$note = $row['note'];

//update the note
if(isset($_POST['save_note_btn'])) {
    $note = $_POST['note'];

    $query = "UPDATE notes SET note = '$note' WHERE note_id ='$note_id'";
    $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
    header("Location: home.php");
}

//delete the note
if(isset($_POST['del_note_btn'])) {
    $query = "DELETE from notes WHERE note_id = '$note_id'";
    $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
    header("Location: home.php");
}

mysqli_close($dbconn);

?>

//This is where note is displayed and edited
<form method="post" action="see_note.php">
    <textarea name="note" placeholder="Your Note" rows="20" cols="140">
        <?php echo $note; ?>
    </textarea>
    <button type="submit" name="save_note_btn">Save</button>
</form>

//Button to delete the note
<form method="post" action="see_note.php">
    <button type="submit" name="del_note_btn">Delete</button>
</form>

代码对我来说似乎很好,我不知道是什么导致了错误。也许我犯了一些愚蠢的错误。请帮忙。

最佳答案

问题是因为以下两行,

//This is where note is displayed and edited
<form method="post" action="see_note.php">
                            ^^^^^^^^^^^^
    ...

//Button to delete the note
<form method="post" action="see_note.php">
                            ^^^^^^^^^^^^
    ...

您需要将注释的 ID 与 action 属性一起附加,如下所示:

//This is where note is displayed and edited
<form method="post" action="see_note.php?id=<?php echo $note_id; ?>">
    ...

//Button to delete the note
<form method="post" action="see_note.php?id=<?php echo $note_id; ?>">
    ...
<小时/>

旁注:

保持这条线不变,

//get id from the URL
$note_id = $_GET['id'];

关于php - 无法在 PHP 中删除或更新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39456864/

相关文章:

php - 将嵌套数组简化为单级数组

php - 调用常量会导致难以理解的解析错误

php - symfony2 多对多奏鸣曲管理模型列表

php - 不使用php函数加密mySql服务器上的数据

Mysql,REGEXP 中的空格

python - 修复列 "date_of_birth"中的空值违反了非空约束

PHP 对 SHOW TABLES 结果运行查询

mysql - 用 mysql float 类型表示十进制数?

mysql - 将网页内容插入数据库

php - 我可以在另一个文件中运行 sql 查询吗?