1

I am a beginner to PHP, currently working on a long survey. Below is the code which is causing issues, the data from the checked boxes are added to a database:

$_q4 = (isset($_GET['check_q4']) ? $_GET['check_q4'] : null);
$q4 = '';
foreach($_q4 as $a4) {
$q4 .= $a4;}


<div class="group v-group">
<label><input type="checkbox" name="check_q4[]" value="1"> Checkbox 1</label>
<label><input type="checkbox" name="check_q4[]" value="2"> Checkbox 2</label>
<label><input type="checkbox" name="check_q4[]" value="3"> Checkbox 3</label>
</div>

Error:

Warning: Invalid argument supplied for foreach() in C:\inetpub\wwwroot\submit_form.php on line 79 Failed to run query: SQLSTATE[22001]: 

Many thanks for you help.

Masiorama
  • 1,066
  • 17
  • 26
pro_flexz
  • 15
  • 3
  • possible duplicate of [Invalid argument supplied for foreach()](http://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – Narendrasingh Sisodia May 12 '15 at 08:59
  • Can you echo out the contents of your `$_q4` variable? It sounds like the $_GET variable is empty, so `null` is being assigned to the variable. Are you actually posting the form via "GET", or are you posting via the "POST" method? – VerySeriousSoftwareEndeavours May 12 '15 at 09:00

2 Answers2

3

Since $_q4 can be null, you should check if it is the case, because you cannot traverse an empty/null variable with foreach.

Try with something like this:

if(!empty($_q4)){
  foreach($_q4 as $a4) {
   $q4 .= $a4;
  }
}
Masiorama
  • 1,066
  • 17
  • 26
0

Please make sure that your Form's request method is get

$_q4 = (isset($_GET['check_q4']) ? $_GET['check_q4'] : null);
$q4 = '';
if(is_array($_q4)){
  foreach($_q4 as $a4) {
  $q4 .= $a4;}
}
kamal pal
  • 4,187
  • 5
  • 25
  • 40