Reputation:
I have a form that asks the user to enter in an exam id that they want to delete from the exam table in the DB.
The problem I am having is that even if the user enters in an id that does not match in the DB the script fires the else block completely ignoring the condition.
I may have implemented this wrong but as far as I am aware of i cannot see where I am wrong but I suspect that there is something I have done wrong in my if statment.
Here is my form that requires the user to enter an exam id for deletion
<form method = "post" action = "examDeleted.php">
<h1 class = "title">Delete Exam</h1>
<div class = "formContent">
<labeL for = "id">ID</labeL>
<input type = text name = "id" class = "input">
<br><br>
<br><br><br>
<input type = "submit" value = "Delete">
</div>
</form>`
This is passed to the function that contains the sql query to delete the record from the table
<?php
include('dbLogin.php');
$id = trim($_POST['id']);
if($id != "")
{
$delete = "DELETE FROM exams WHERE id = '$id'";
$results = mysql_query($delete);
if(!$results)
{
die ("Cannot delete data from the database! " + mysql_error());
echo '<br><br>';
echo '<a href="home.html">Return</a>';
}
else
{
echo"Exam: $id has been deleted";
}
}
else
{
echo "No data entered! " . mysql_error();
}
?>
As you can see the condition !$results
, to me it is saying if the record does not exist then kill the query else confirm the deletion. Is there an obvious reason why the inner if statment dosent get fired?
Upvotes: 0
Views: 2941
Reputation: 38238
DELETE
statements are considered successful even if no rows were deleted. (This is how SQL works in general; it's not MySQL-specific.)
I would say that you should use mysql_affected_rows to find out how many rows were deleted, but as others have pointed out, you shouldn't be using the mysql_ functions at all, anyway.
Your code as it stands is highly vulnerable to SQL injection attacks. If someone were to POST the following ID to examDeleted.php (remember, they don't have to use your form to do that, so any client-side checks can be bypassed):
' OR 1 = 1 OR id = '
...I think it would probably delete every exam in your table, as your SQL statement would end up as:
DELETE FROM exams WHERE id = '' OR 1 = 1 OR id = ' '
...which is a valid DELETE statement whose WHERE clause matches all your rows.
Using parameterised queries (available in the non-deprecated MySQL drivers like mysqli or PDO) would combat this issue.
Upvotes: 1