0

I have a list of IDs generated from a set of checkboxes as follows:

$list = mysql_real_escape_string(implode(',',$_POST['checkbox']));

which outputs a list like this:

a,b,c

I want to set a column in a MYSQL database that corresponds to each list item, I am unsuccessfully trying to create a query with a foreach loop like so:

$update_query= '';
foreach($list as $item){     //error on this line
 $update_query .= "
  INSERT INTO t (Col_1, Col_2)
  VALUES  ('".$item."',now());
     ";}

It fails telling me I have supplied an invalid argument for foreach(), but I'm not sure, a. what that means, and b. how to fix it; can anyone offer any guidance to get my loop working or a better way of doing this INSERT.

Thanks

2
  • 2
    RTLM: php.net/foreach php.net/implode Commented Feb 27, 2013 at 16:01
  • I do check the php manual before I post here, but as I'm self taught with ~3months knowledge I often find them difficult to understand. Regardless, thanks for taking the time to read my question :) Commented Feb 27, 2013 at 16:18

1 Answer 1

3

$list is a string, not an array. Try passing in the array before you have imploaded it:

$update_query= '';

foreach($_POST['checkbox'] as $item)
{
    $update_query .= "INSERT INTO t (Col_1, Col_2) VALUES ('".addslashes($item)."', now());"; 
}

You'd be much better off using prepared statements, though!

Sign up to request clarification or add additional context in comments.

1 Comment

That works perfectly, thank you very much. Could you give me an example of how to use a prepared statement in this case?

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.