0

I have a simple form, e.g:

HTML:

Your favorite food?
 Pizza: <input type="checkbox" name="food[]" value="0" />
 Beef: <input type="checkbox" name="food[]" value="1" />
 Eggs: <input type="checkbox" name="food[]" value="2" />

Your Email?
  <input type="text" name="email" /> 

I could get the result via foreach():

foreach($_POST['food'] as $food) { 
  echo $food;
}


Where I should put the Insertion query when the user choose more than one food:


$query = $DB->insert("INSERT INTO table VALUES('NULL','$food','$email')");

BS:

I should insert one row even if the user choose 3 foods. The food field accept more than one value

example:

user 1:

email: david@gmail.com
food: 1


user 2:

email: jack@gmail.com
food: 0 1 2 
Cheerio
  • 1,148
  • 6
  • 17
  • 35

2 Answers2

4

You should put this query in foreach if you want to save each record in new row.

$query = array();
foreach($_POST['food'] as $food) { 
  $query[] = "('NULL','$food','$email')";
}
$query = $DB->insert("INSERT INTO table VALUES ".implode(',', $query).");

or if you want to store all foods in single row then you can use as

$foods = implode(',', $_POST['food']);
$query = $DB->insert("INSERT INTO table VALUES('NULL','$foods','$email')");

This will save foods in format of food1,food2,food3

Gaurav
  • 26,880
  • 8
  • 47
  • 76
  • 1
    it would make 3 queries for `food1,food2,food3` – delphist Feb 26 '11 at 10:05
  • `INSERT INTO table VALUES('NULL','food1','email@example.com')`, `INSERT INTO table VALUES('NULL','food2','email@example.com')`, `INSERT INTO table VALUES('NULL','food3','email@example.com')` – delphist Feb 26 '11 at 10:08
  • I have this code in the begin `foreach($_POST as $key => $value){ $_POST[$key] = mysql_real_escape_string(strip_tags($value)); } ` and it avoid the new code: `$foods = implode(',', $_POST['job']);` – Cheerio Feb 26 '11 at 10:30
  • string_tags works with string not array. And in foreach you were is using it with array. was it working. You can use mysql_real_escape_string(strip_tags(implode(',', $_POST['job']))); – Gaurav Feb 26 '11 at 10:38
  • I have a lot of fields :) so I have a foreach in the begin with mysql_real_escape_string for the all fields as I mentioned in the comment above – Cheerio Feb 26 '11 at 11:50
0
$query_body = array();
foreach($_POST['food'] as $v) { 
  $query_body[] = '(\'NULL\', \''.addslashes($v).'\', \''.addslashes($email).'\')';
}

if(count($query_body)) {
  $query = 'INSERT INTO table VALUES '.implode(',', $query_body);
}
delphist
  • 4,307
  • 1
  • 20
  • 22