php - 从复选框中获取所有值?

标签 php html mysql checkbox

<分区>

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

<?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>

最佳答案

如果您为复选框指定相同的名称,以 [] 结尾,则值将作为数组返回。

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

然后在 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.
}

附言。请原谅这个明显的错误,这个例子可能会大喊“我有一个苹果”......我没想到让这个例子足够聪明来确定什么时候使用“a”,什么时候使用“an”:P

关于php - 从复选框中获取所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5182938/

相关文章:

php - 基于逗号分隔值条件的 SQL 查询?

MySQL/MariaDB 写入/插入需要很长时间

php - 生成单词组合

javascript - PHP/将数字作为字符串发布,intval无法将其转换为数字

php - golang 相当于 PHP crypt()

javascript - 如何获取“检查元素”中显示的网站数据,而不是“查看页面源”中显示的网站数据?

java - 如何使用 Struts2 和 Hibernate 删除和修改数据

php - 如何避免以明文形式存储我需要访问的用户密码?

html - Fontastic 未在移动设备上加载

Javascript 日期验证 (DD/MM/YYYY) & 年龄检查