复选框选中或取消选中boolean php mysql

时间:2012-01-31 21:13:23

标签: php checkbox boolean checked unchecked

我正在尝试使用复选框获取值1或0,排序为布尔值,并在mysql上更新它,但我还没找到方法。也许你可以帮忙。我将发布表单和接收它的代码。我确信可能存在循环冲突,但我尝试了一切并且无法使其正常工作。请事先提前。

表格

<form action="esconde_cat.php" method="post">
    <table width="300px" align="center" width="140" border="1">
        <tr>
            <td></td>
            <td width="200">Categoria</td>
            <td width="100">Mostrar</td>
        </tr>
        <?php
            include "conecta.php";
            include "verifica.php";

            $sql = "SELECT * FROM categorias ORDER BY ordem";
            $res = mysql_query($sql) or die (mysql_error());
            while ($linha=mysql_fetch_array($res)) {
        ?>
        <tr>
            <td><input name="user[]" type="checkbox" value="true"/></td>
            <td><?=$linha['1']; ?></td>
            <td><?php if ($linha['3'] == TRUE){ echo 'SIM'; } else {echo 'NÃO'; } ?></td>
            </td>
        </tr> 

        <?php 
            }
        ?>
    </table>
    <br/>
    <table align="center">
        <tr>
            <td>
                <input type="submit" name="Delete" type="button" value="Alterar">
            </td>
        </tr>
    </table>
</form>

收到表格并更新MYSQL的代码

<?php

include "conecta.php";
include "verifica.php";

\\THIS PART WORKS, GETS IF THE CHECKBOX IS CHECKED AND RECORD IT ON DB

if(isset($_POST['user'])) {
    foreach ($_POST['user'] as $key => $read){
        $read =(@$_POST['user']=='0')? $_POST['user']:'1';
        echo $read;
        $sql = "UPDATE categorias SET mostrar='$read' WHERE ordem='$key'";
        $res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
    }
}

\\ON THIS PART OF THE CODE THAT I CANT GET THE VARIABLE TO GET THE
\\VALUE FROM CHEBOXES THAT ARE UNCHECKED RECORDED TO DATABASE

if (!isset($_POST['user'])) {
    foreach ($_POST['user'] as $chave => $leia) {
        $leia =(@$_POST['user']=='1')? $_POST['user']:'0';
        echo $leia;
        $sql = "UPDATE categorias SET mostrar='$leia' WHERE ordem='$chave'";
        $res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
    }
}

?>

1 个答案:

答案 0 :(得分:4)

如果未选中复选框,您将在$_POST变量中获得NO键。如果已选中,则将设置密钥,该值将为复选框的值。

假设“user []”的名称有效,例如:

<input type="checkbox" name="user[]" value="aa" />
<input type="checkbox" name="user[]" value="bb" checked="checked" />
<input type="checkbox" name="user[]" value="cc" checked="checked" />
<input type="checkbox" name="user[]" value="dd" />
<input type="checkbox" name="user[]" value="ee" checked="checked" />

您希望$_POST为:

array(
    "user" => array(
        "1" => "bb"
        "2" => "cc"
        "4" => "ee"
    )
);