doctorsherlock
doctorsherlock

Reputation: 1374

Not able to delete or update a row in PHP?

I am working on my first PHP app that is a simple notes taking application. I am using different URLs for the notes like this -

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

So, the primary key acts as parameter for the URL of a note. The link redirects me to the note without any problem, but when I try to delete or update the note it throws this error -

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

Line 17 is where I am extracting the id from the URL -

$note_id = $_GET['id'];

Here is the rest of the code for the page displaying the note-

//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>

The code seems fine to me, I have no idea what is causing the error. Maybe I have made some silly mistake. Please help.

Upvotes: 0

Views: 51

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

The problem is because of the following two lines,

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

and

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

You need to append the note's id along with the action attribute, like this:

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

and

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

Sidenote:

Keep this line as it is,

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

Upvotes: 2

Related Questions