Search code examples
phparrayspostdynamic-data

$_POST value from array of input type="image" array?


I have a dynamic list of items pulled from a database, where the list contains 0 to N items. Each item is listed in a row in an HTML table with an submit button. I need to know which of these buttons, specifically, is clicked on $_POST and to obtain the value of that item.

My present approach is to use an array. However, the $_POST value returns all items in the array, not only the item that was clicked. What's more, the array values do not correlate to the values pulled from the database. The same image submit button may be clicked repeatedly and produce different values.

<?php
else if (isset($_POST["deleteItem"]))
{   
    foreach ($_POST["deleteItem"] as $value) :
        WishList::Delete($value);
    endforeach; 
}
?>

<form method="post" action="">
    <table id="WishListTable">
<?php
    $wishlist = WishList::GetAllByID($userID);
    foreach ($wishlist as $item)
    {
    echo "<tr><td>" . $item->Description . "</td>";
    echo "<td>";
    if ($item->InStock)
    {
        $primaryEmailAlreadyUsed = true;
        echo "In Stock";
    }
    else {
        echo "Out of Stock";
    }
    echo "</td>";
    echo "<td style=\"text-align:center;\"><input type=\"image\" src=\"/images/deleteX.gif\" border=\"0\" alt=\"Delete\" id='" . $iteml->ID . "' name=\"deleteItem[]\" value=\"" . $item->ID . "\" ></td>";
    echo "</tr>";
}
?>
</table>
</form>

Solution

  • Try changing

    name=\"deleteItem[]\"
    

    to

    name=\"deleteItem[" . $item->ID . "]\"
    

    On submit, the sole member of deleteItem would be deleteItem[ID]

    list($deletedItemID) = array_keys($_POST['deleteItem']);