-2

I have an Interest areas in my page when i register new user and when leaving Interest Area selection filed default (empty) I'm getting this error Here is the code:

    91-    //Interest
    92-     foreach ($_POST['interest_id'] as $interest)
    93-     {
    94-         $query = "INSERT INTO user_interest (user_id, interest_id)
    95-                 VALUES  ('$user_id', '$interest')";
    96-         $result = mysqli_query($link,$query);
    95-     }

and this is my Interest Areas part in the page :

<label>Research Areas</label>
      <select name="interest_id[]" class="small-input" multiple>
        <?php 
            $query = "SELECT * FROM research_interest ORDER BY name ASC";
            $result = mysqli_query($link, $query);
            while($row = mysqli_fetch_object($result))
            {
        ?>
            <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
        <?php
            }
        ?>
      </select>
    </p>
  • ...put a `if(isset($_POST['interest_id']) and is_array($_POST['interest_id'])){}` around your loop? – Scuzzy Apr 14 '14 at 23:38

1 Answers1

3

This is self explanatory, $_POST['interest_id'] is a string value but foreach expects an array.

 $interest = (int) $_POST['interest_id'];
 $query = "INSERT INTO user_interest (user_id, interest_id) 
           VALUES  ('$user_id', '$interest')";
 $result = mysqli_query($link,$query);

or if you are passing an array (you are, didn't read that until after I posted all this above), you should be testing that it's not empty first:

if(!empty($_POST['interest_id']) && is_array($_POST['interest_id'])) {
foreach ($_POST['interest_id'] as $interest)
{
  $query = "INSERT INTO user_interest (user_id, interest_id)
  VALUES  ('$user_id', '$interest')";
  $result = mysqli_query($link,$query);
} }
skrilled
  • 5,350
  • 2
  • 26
  • 48
  • 1
    the square bracket notation of `name="interest_id[]"` should create an array when populated from the form data. – Scuzzy Apr 14 '14 at 23:40