Home  >  Article  >  php教程  >  PHP中获得复选框是否选中并写入数据库

PHP中获得复选框是否选中并写入数据库

WBOY
WBOYOriginal
2016-05-25 16:47:291283browse

下面我们总结了关于PHP中获得复选框是否选中并写入数据库 有需要学习的朋友可参考参考.

form.html实例代码如下:

<form action=checkbox.php method=post>  
<input name="s[]" type="checkbox" value="3" />3<br>  
<input name="s[]" type="checkbox" value="7" />7<br>  
<input name="s[]" type="checkbox" value="1" />1<br>  
<input name="s[]" type="checkbox" value="15" />15<br>  
<input type=submit>  
</form>

然后建立一个处理表单的程序:

checkbox.php实例代码如下:

<?php   
$a=$_POST["s"];  
print_r($a);  
?>

但是上面这个程序只是用来显示复选框是否正常,如果逐个取出数组中所有的数据,需要用到循环.所以进一步将程序修改为:

checkbox.php实例代码如下:

<?php   
$a=$_POST["s"];  
for($i=0;$i<count($a);$i++)  
{  
    echo "选项".$a[$i]."被选中<br />";  
}  
?>

这样执行的结果类似于:

选项3被选中

选项15被选中

利用javascript做一下预处理.多个同名复选框在javascript中还是以数组的形式存在的,所以在表单提交之前可以利用javascript把复选框中的信息组合成一个字符数组赋值给表单中的隐藏元素,然后用php中的explode函数解析此数组,这样就可以实现复选框信息的传递了.下面举例说明. 

假设有这样一个表单:

实例代码如下:

<form name="form1" id="form1" method="post" action="myphp.php" onsubmit="return checker()"> 
<input type="checkbox" name="item" value="1">1<br> 
<input type="checkbox" name="item" value="2">2<br> 
<input type="checkbox" name="item" value="3">3<br> 
<input type="checkbox" name="item" value="4">4<br> 
<input type="hidden" name="items" value=""> 
<input type="submit" value="submit"> 
</form>

这个表单有四个名字都是item的复选框,当用户单击submit按钮的时候,checker函数会被调用,并且如果checker返回true表单就被提交,返回false表单就不会被提交.这里checker函数就是我们要编写的预处理函数.在html的header部分添加下面的javascript:

实例代码如下:

<script language="javascript">  
<!--  
function checker() {
    form1.items.value = "";
    if (!form1.item.length) // 只有一个复选框,form1.item.length = undefined
    {
        if (form1.items.checked)
            form1.items.value = form1.item.value;
    } else {
        for (i = 0; i < form1.item.length; i++) {
            if (form1.item(i).checked) // 复选框中有选中的框
            {
                form1.items.value = form1.item(i).value;
                for (j = i + 1; j < form1.item.length; j++) {
                    if (form1.item(j).checked) {
                        form1.items.value += " "; //用空格做分割符
                        form1.items.value += form1.item(j).value;
                    }
                }
                break;
            }
        }
    }
    return true;
}
-->  
</script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn