Trying to use a foreach statement to delete all selected items

Posted on 2009-02-18
Last Modified: 2012-05-06
I am trying to delete items in the database using a foreach statement, but am having a tough time understanding the foreach statement.  This is what I have so far, but I am getting the error:

Warning: Invalid argument supplied for foreach()

if($_POST['dID']) {
            foreach($_POST['dID'] AS $dID) {
                  $deleteItem = sprintf("DELETE
                        FROM category_items
                        WHERE id=%d", $dID);
                  $itemDeleted = mysql_query($deleteItem) or die("Delete did not work because: " . mysql_error());
Question by:pingeyeg
    LVL 17

    Accepted Solution

    Sounds like $_POST['dID'] is not an array.

    if your using check boxes, in the name field add [] to the name, this will make that value into array

    <input type="checkbox" name="dID[]' value="true" />

    LVL 14

    Assisted Solution

    by:Ionut A. Tudor
    Gives you error because its not an array, see below how to check if its array or not

    $dID = $_POST['dID'];
    if(isset($dID)) {
    				echo "use foreach";
    				echo "don't use foreach as this is not an array";

    Open in new window

    LVL 8

    Expert Comment

    have you tried "al3sc12" solution yet ????? waiting your reply
    LVL 1

    Author Comment

    Sorry, got side tracked.  Yes, and it worked great!  Thanks!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now