获取复选框的所有值? [英] Get all values from checkboxes?

查看:98
本文介绍了获取复选框的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来获取多个复选框的值并将它们存储在数据库中?

 <?php 
if(isset($ _ POST ['go'])){
$ fruit = $ _POST ['fruit']。,;
echo $ fruit;
//如果您选择了苹果和柚子,它会显示苹果,葡萄柚
}
?>
< form method =post>
选择您最喜欢的水果:< br />
< input type =checkboxname =fruitvalue =appleid =apple/>< label for =apple> Apple< / label>< br /> ;
< input type =checkboxname =fruitvalue =pinappleid =pinapple/>< label for =pinapple> Pinapple< / label>< br /> ;
< input type =checkboxname =fruitvalue =grapefruitid =grapefruit/>< label for =grapefruit>葡萄柚< / label>< br /> ;
< input type =submitname =go/>
< / form>


解决方案

如果您给复选框使用相同的名称,

 < input type =checkboxname =fruit [] value =apple/> 
< input type =checkboxname =fruit []value =grapefruit/>

然后在PHP中...



<$ p ($ _ POST ['fruit'])&& is_array($ _ POST ['fruit'])){
foreach($ _ POST ['fruit'])$ p> 作为$ fruit){
// eg。 我有一个葡萄柚!
回声我有一个{$ fruit}!;
// - 插入数据库调用可能会在这里
}

// eg。 apple,grapefruit
$ fruitList = implode(',',$ _POST ['fruit']);
// - 插入数据库调用(for fruitList)可能会在这里。
}

PS。请原谅明显的错误,这个例子可能会大喊我有一个苹果......我没有想到让这个例子足够聪明以确定何时使用a,何时使用an:P

Is there an easy way to get the values of multiple checkboxes and store them in the database?

<?php
if(isset($_POST['go'])){
   $fruit = $_POST['fruit'].",";
   echo $fruit;
   // if you selected apple and grapefruit it would display apple,grapefruit
}
?>
<form method="post">
Select your favorite fruit:<br />
<input type="checkbox" name="fruit" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
<input type="checkbox" name="fruit" value="grapefruit" id="grapefruit" /><label for="grapefruit">Grapefruit</label><br />
<input type="submit" name="go" />
</form>

解决方案

If you give the checkboxes the same name, ending in [], the values are returned as an array.

<input type="checkbox" name="fruit[]" value="apple" />
<input type="checkbox" name="fruit[]" value="grapefruit" />

Then in PHP ...

if( isset($_POST['fruit']) && is_array($_POST['fruit']) ) {
    foreach($_POST['fruit'] as $fruit) {
        // eg. "I have a grapefruit!"
        echo "I have a {$fruit}!";
        // -- insert into database call might go here
    }

    // eg. "apple, grapefruit"
    $fruitList = implode(', ', $_POST['fruit']);
    // -- insert into database call (for fruitList) might go here.
}

PS. please forgive the obvious error, that this example will potentially shout "I have a apple" ... I didn't think to make the example smart enough to determine when to use "a", and when to use "an" :P

这篇关于获取复选框的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆