开发者

Foreach with PHP

开发者 https://www.devze.com 2023-02-14 02:27 出处:网络
I have a simple form, e.g: HTML: Your favorite food? Pizza: <input type=\"checkbox\"开发者_JS百科 name=\"food[]\" value=\"0\" />

I have a simple form, e.g:

HTML:

Your favorite food?
 Pizza: <input type="checkbox"开发者_JS百科 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 


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


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

精彩评论

暂无评论...
验证码 换一张
取 消