PHP复选框作为布尔值 [英] PHP check boxes as boolean values

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

问题描述

我需要在SQL中使用复选框中的数据创建首选项表。这就是池,按摩浴缸,后院,智能房子是在首选项中的列,TINYINTS表示布尔T或F.当用户选中一个框,我想要的值为1,否则它保持在0.所以说,一个游泳池和一个后院,并检查那两个盒子。我的$ _POST [preferences]将是一个数组[1,0,1,0]。

I need to create a Preferences table in a SQL using data from checkboxes. That is Pool,Jacuzzi, Backyard, Smart House are columns in Preferences that are TINYINTS to represent Boolean T or F. When a user checks a box, I want the value to be 1, else it stays at 0. So say a user wants a Pool and a Backyard and checks those two boxes. my $_POST[preferences] would be an array that would be [1,0,1,0].

<input type="checkbox" name="preferences[]" value="Pool"> Pool<br>
<input type="checkbox" name="preferences[]" value="Jacuzzi"> Jacuzzi<br>
<input type="checkbox" name="preferences[]" value="Backyard"> Backyard<br>
<input type="checkbox" name="preferences[]" value="Smart"> Smart House<br>

更新:
好​​的,这是关闭。这是我有一些类似于这,但我不能告诉它是否实际上给一个值为1或0.如果它是1,它显示在数组,但如果它没有被检查,它不是。所以它最终是[池,按摩浴缸]。我不知道,如果他们的值为1,其他的值为0,或者它只是暗示。

UPDATE: Ok yes this is close. This is what I have which is somewhat similar to this, however I can't tell if it is actually giving a value of 1 or 0. If it's 1, it shows up in the array but if it's not checked it doesn't. So it ends up being [Pool,Jacuzzi]. I am not sure though if they have the value of 1 and the other ones have a value of 0, or is it just implied.

foreach ($preferences as $key => $val) {
if(isset($key)){
$val=1;
}
else{
$val = 0;
}
}

UPDATE2:解决方案我发现工作类似@ chris85

UPDATE2: Solution I found to work kind of similar to @chris85

 ** I found out that keeping hidden checkboxes would work for defaulting values to zero if they arent checked.

 <input type="hidden" name="pool" value="0"/>
 <input type="checkbox" id="pool" name="pool" value="1">Pool<br>

 $low= $_POST['low'];
 $high =$_POST['high'];
 $pool = $_POST['pool'];
 $jacuzzi= $_POST['jacuzzi'];
 $backyard= $_POST['backyard'];
 $smart= $_POST['smart'];
 $addPreferences = "INSERT INTO Preferences(Pool,Jacuzzi,Backyard,Smart)
 VALUES ('$pool','$jacuzzi','$backyard','$smart')";


推荐答案

$magic['pool'] = 0;
$magic['smart'] = 0;
$magic['jacuzzi'] = 0;
$magic['backyard'] = 0;
if(!empty($preferences)){
    foreach($preferences as $preference) {
        $magic[$preference] = 1;
    }
}
print_r($magic);

输出:

Array
(
    [pool] => 0
    [smart] => 0
    [jacuzzi] => 0
    [backyard] => 0
)

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

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