Skip to content
Advertisement

Deleting record outputs else statement of else 3 times after deleting record in PHP and SQL

I am trying to delete a record in php mysql but my code jumps me to the else statement where I have “record not deleted” message printed out. Strangely it prints out 3 times. I am attempting to have it simply show an alert when the record is deleted to keep things simple. I know I am connected to the db as I can see my records on the screen.

I can see the sql id record in the address bar so I also know it is going for the correct record but on the screen, I see – Error Deleting RecordError Deleting RecordError Deleting Record

I am sure it is a simple thing but for the life of my, I just can’t seam to identify where I could have gone wrong. If anyone can help me spot the issue, I would surely appreciate it.

My code is as follows –

user-data.php

deletecode.php

Again, if anyone can help me out here, I would surely appreciate it. Thank you in advance.

Advertisement

Answer

Okay… Firstly, let’s reformat your code:

Basically what is happening here is that you firstly SELECT all of your users (I’m going to assume that you have four in your DB?) and then you iterate over each of them in your while loop.

In the first iteration it probably deletes the record and the script code should be output (obviously you won’t see this) without viewing source.

In every subsequent iteration the DELETE fails because the record has already been deleted. Therefore the error message is output.

N.B.

  1. You will never redirect with the header function because you’ve already output something with echo.
  2. You must use a prepared statement in this scenario (where you have user supplied data) to protect your DB
  3. You really should be checking that your user who is doing the delete has the permission to do it (e.g. is logged in as admin); otherwise anyone could do it?
  4. Most people would advise you against using a GET request for a DELETE action.
  5. Most people, again, would advise you to start to learn PDO and do away with the procedural mysqli_* calls. Or, at least, use the OOP mysqli-> format.
  6. You should really ensure that you enable error reporting in mysqli as well

What you actually want to do is just run the delete query and check that it completed:

Preferred solution

  • Using PDO to connect to the DB
  • Using a form to POST the delete request
  • With a check to make sure permissions are correct
  • Using prepared statements

user-data.php

deletecode.php

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement