-1

I'm an getting the error

Warning: Invalid argument supplied for foreach()

in my code. But this is due to my checkboxes not being submitted in a form which is in another page. Can I somehow avoid showing the error or code something to check if submit is set before it throws out an error?

In my page2.php I have 10 checkboxes that display data. Once selected and submitted, it write the data using an echo and a foreach() loop on page1.php. But the problem is that when I load page1.php before page2.php is submitted I obviously get an error is there a way around this? Thanks.

my code on breakfast.php is:

error_reporting( E_ALL & ~E_NOTICE );

if (isset($_POST['submit'])) 
{
    $foodchoice = $_POST['meal'];
}

?>

my code on homePage.php is :

if (isset($_POST['meal'])) 
{
   echo "yay!";
}

if (!isset($_POST['meal']))
{
    echo "nay!";
}

code that brings up the error on homePage.php:

<div id="equip" class="doc"> <section> <h3 id="title6"> Catering Selections </h3> </section> 
<center>

<?php  


foreach($_POST['meal'] as $checkbox){
    echo "</br> <li> ".$checkbox . '</li> ' ;
}  ?>


</center>
</div>

form data on breakfast.php

<form action="homePage.php" method="post">

 <input type='checkbox' value='The Share Collection' name = "meal[]" id='button3'>

<input type='checkbox' value='Assorted Biscuits' name = "meal[]" id='button3'>

<input type='checkbox' value='Fruit Skewers' name = "meal[]" id='button3'>

<input type='checkbox' value='Bread Project' name = "meal[]" id='button3'>
 <input type='checkbox' value='Cheese Project' name = "meal[]" id='button3'>

<input type="submit" id="button4" value="Submit Your Selection" name="submit">

On first load of homePage.php the result from the isset statement is nay and once submitted from breakfast.php it says yay! Please advise on a workaround. Thanks

Picone92
  • 9
  • 5

2 Answers2

0

$foodchoice = $_POST['meal[]']; is the incorrect way to reference it.

just use

$foodchoice = $_POST['meal'];

then $foodchoice will be an array that you can loop through.

Brett
  • 1,951
  • 2
  • 28
  • 35
0

You could use $_SERVER['HTTP_REFERER'] to check which page the user came from. Use it in an if statement to see if the user came from page 2.

Another option is adding a GET variable to the link that sends you from page 2 to page 1, on page 1 you could check if this variable is present to see if the result of the checkbox should be shown.

yarwest
  • 873
  • 8
  • 19