我正在开发我的第一个 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/