maham.shahid
maham.shahid

Reputation: 301

Error deleting rows from mysql database using PHP

I'm having trouble deleting rows from the database. I try to bind the parameter (id) according to which a row has to be deleted. It returns success message that the row has been deleted but the row is not actually deleted from the database. Here's the code where I'm calling the delete script using ajax:

<script>
    $("#del").click(function(){
        var id;
        $("input:checked").each(function(){
            id=$(this).parent().parent().children(".id").html();
        });
        var datastring=JSON.stringify(id);
        $.ajax({
            type:'post',
            url:'delete.php',
            data: {data:datastring},
            success: function(data){
                alert(data);
            }
        });
    });
</script>

Here's the delete script (delete.php)

if(isset($_POST["data"]))
{
    $id=$_POST["data"];
    $db=mysqli_connect("localhost","root","","products");
    if($db)
    {
        $query=mysqli_prepare($db,"DELETE FROM product_info WHERE prod_id=?");
        $query->bind_param('i',$id);
        $result=$query->execute(array($id));
        if($result)
            echo "Deleted successfully";
        else
            echo "Error in deletion of product";
        $query->close();
    }
    else
        echo "Error Connecting to DB";
}
else
    echo "POST not set";

The statement "Deleted successfully" is echoed back and alerted but the row is not actually deleted from the database. If i omit the bind_param part and directly specify the id in the query, then the record is deleted. Help!

Upvotes: 0

Views: 934

Answers (1)

maham.shahid
maham.shahid

Reputation: 301

Ok so the issue has been resolved. The statement causing the problem was this one:

var datastring=JSON.stringify(id);

Instead, I did this in the ajax call

$.ajax({
            type:'post',
            url:'delete.php',
            data: {data:id},  //instead of sending datastring, I sent the id directly
            success: function(data){
                alert(data);
            }
  });

Upvotes: 0

Related Questions