Cheerio
Cheerio

Reputation: 1240

Foreach with PHP

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: [email protected]
food: 1


user 2:

email: [email protected]
food: 0 1 2 

Upvotes: 0

Views: 336

Answers (2)

Gaurav
Gaurav

Reputation: 28755

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

Upvotes: 4

delphist
delphist

Reputation: 4539

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

Upvotes: 0

Related Questions