Jump to content

foreach Warning!


balkan7

Recommended Posts

i have problem whit delete product, just delete latest product added, here is the code of warning:
[code]<td><input type='checkbox' name='row[]' value='$row[id]'></td>
<tr><td><p align='right'><input type='submit' name='delete' value='Delete'></td></tr>
[/code]

[code]case "delete":
      //if nothing is submitted in the
      //row[] array, then error!
      if(empty($_POST['row']))
      {
          echo "Nothing to delete!";
      }
      if(isset($_POST['delete']))
      {
          $delete_array = $_POST['row'];
     
          //loop through each individual
          //item in the array
         
          foreach($delete_array as $val)
          {
                //delete them!
                $query = "DELETE FROM software WHERE id = '$val'";
                $result = mysql_query($query) or die(mysql_error());
          }
          echo "Product has been successfull delete!";
      }
      break;
[/code]

and show me:
[code]Nothing to delete!
Warning: Invalid argument supplied for foreach() in /home/xxx/public_html/test/index.php on line 256
Product has been successfull delete![/code]
Link to comment
https://forums.phpfreaks.com/topic/26821-foreach-warning/
Share on other sites

You can check whether [b]$delete_array[/b] is an array using [b]is_array()[/b] function and only then process the foreach loop. Like this:-
[code]if(is_array($delete_array))
{
          foreach($delete_array as $val)
          {
                //delete them!
                $query = "DELETE FROM software WHERE id = '$val'";
                $result = mysql_query($query) or die(mysql_error());
          }
}[/code]
Link to comment
https://forums.phpfreaks.com/topic/26821-foreach-warning/#findComment-122643
Share on other sites

Here is the solution:

[code]
case "delete":
      //if nothing is submitted in the
      //row[] array, then error!
    if(isset($_POST['delete'])) {
        if(empty($_POST['row']))
      {
          echo "Nothing to delete!";
      } else {
          $delete_array = $_POST['row'];
     
          //loop through each individual
          //item in the array
         
          foreach($delete_array as $val)
          {
                //delete them!
                $query = "DELETE FROM software WHERE id = '$val'";
                $result = mysql_query($query) or die(mysql_error());
          }
          echo "Product has been successfull delete!";
      }
  }
      break;
[/code]

Just a simple else statement was needed and a little line change.
Link to comment
https://forums.phpfreaks.com/topic/26821-foreach-warning/#findComment-123826
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.