virtuon92
virtuon92

Reputation: 49

Delete specific value from table

 $result = mysqli_query($conn,"select * from `favourites` WHERE user_id = '$session'");
    while($row = mysqli_fetch_assoc($result)) { ?>

      <input type="hidden" value="<?php echo $row['id']; ?>" name="name"/>

       <?  $pid=$row['id'];

    }

    if(isset($_POST['delete'])) {
     $delete="DELETE FROM `favourites` WHERE id = '$pid' AND user_id = '$session'";
        if (mysqli_query($conn, $delete)) {
            echo "Record deleted successfully " . $id;
        } else {
            echo "Error deleting record: " . mysqli_error($conn);
        }
}

So the story of this page is to display all the images witch are favoured by the user (Witch works).Now of course if user wants to remove them,i added "delete" button.But the problem is,It only deletes the last picture when i press the button on any of the pictures.For example,i have pictures with IDs : 10,11,12,13...and they are displayed in that order too.So when i press delete on for exmp picture 11,it will delete picture 13.So basicly no matter what picture i want to remove from table,it always removes the last one. Iv put hidden button in while loop to get the pictures ID,and set a delete condition in If statment to delete when that id is equal to the id in the table.

Any ideas what am i doing wrong ?

Edit-The delete form :

    <form method="post">
<input type="hidden" value="<?php echo $row['name']; ?>" name="name"/>
<input type="hidden" value="<?php echo $row['id']; ?>" name="nameid"/>
<button type="submit"  class="btn btn-danger btn-circle" name="delete"><i class="glyphicon glyphicon-remove"></i></button>

                                        </form>

Upvotes: 0

Views: 62

Answers (2)

D.k
D.k

Reputation: 462

Your form is posting the ID of the pic to be deleted having name "nameid". so in delete query use the ID posted.

if(isset($_POST['delete'])) {
 $delete="DELETE FROM `favourites` WHERE id = '".$_POST['nameid']."' AND user_id = '$session'";
    if (mysqli_query($conn, $delete)) {
        echo "Record deleted successfully " . $_POST['nameid'];
    } else {
        echo "Error deleting record: " . mysqli_error($conn);
    }
}

Upvotes: 1

WebInsight
WebInsight

Reputation: 307

DELETE FROM `favourites` WHERE id = '$pid'

this $pid will have the last id after the while loop will end,thereby only deleting the last one

Upvotes: 1

Related Questions