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.

2
  • possible duplicate of Invalid argument supplied for foreach() Commented May 12, 2015 at 8: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? Commented May 12, 2015 at 9:00

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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;}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.