4

This is the code I'm using for deleting row from my DB:

<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";

if ($con->query($query)==TRUE)
{
    echo " record deleted";
}
else 
{
    echo "Error: " . $query . "<br>" . $con->error;
}

$con->close();
?>

The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.

Why is this happening? how can I verify that my record has been deleted from my DB?

dWinder
  • 11,597
  • 3
  • 24
  • 39
  • 4
    Because the query executes successfully even if there is no data deleted.You need to access mysqli_info() to check whether records are deleted or not. – Madhur Bhaiya Dec 02 '18 at 07:41
  • 3
    Moreover, your code is open to [SQL injection](https://stackoverflow.com/q/332365/2469308) related attacks. Please learn to use [Prepared Statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) instead. – Madhur Bhaiya Dec 02 '18 at 07:42
  • The records are deleted in the database if the records are found. And also it displays "record deleted" even if the records are not available in the database. – Sharique Ahmed Dec 02 '18 at 07:55
  • 1
    Query executes successfully in both the cases whether any records are deleted or not. If you want to check whether actually any records got deleted or not, take a look at: http://php.net/manual/en/mysqli.affected-rows.php – Madhur Bhaiya Dec 02 '18 at 07:59

1 Answers1

7

You can use mysqli.affected-rows.

Consider the following:

$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
    echo " record deleted";
} else {
    echo "Error: " . $query . "<br>" . $con->error;
}
dWinder
  • 11,597
  • 3
  • 24
  • 39