PHP/MySQL更新复选框到数据库的选择 [英] PHP/MySQL Update checkbox selection to database

查看:90
本文介绍了PHP/MySQL更新复选框到数据库的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据库字段更新为1或0,具体取决于是否选中了此复选框.

I'm trying to update a database field with a 1 or 0, depending on whether a checkbox is checked or not.

似乎已选中该复选框,但没有显示为空.

It seems to work when the checkbox is checked but not when empty.

任何想法如何解决这个问题?下面的代码.非常感谢,S.

Any ideas how to solve this? Code below. Many Thanks, S.

这是我表单中的代码:

$query  = "SELECT * FROM istable WHERE assocProp = '".$_POST['id']."'";
    $result = mysql_query($query);              
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
        {                                           
        echo '<li>                          
                <label for="changePP'.$row['id'].'"><input id="changePP'.$row['id'].'" type="checkbox" name="showPP_ids[]" value="'.$row['id'].'"'.($row['showPP']=='1' ? ' checked="checked"':NULL).' /> Display</label>
                </li>'. PHP_EOL;                                        
        } 

以及php进程代码(已更新):

And the php process code (updated):

$newQuery=mysql_query("select * from ispdfs where assocProp = '".$_POST['id']."'");
    $newResult=mysql_fetch_array($newQuery);    

    foreach ($newResult as $showPP_ids) {
      $val = (int) isset($_POST['showPP_ids']); 
        mysql_query("UPDATE ispdfs SET showPP = $val WHERE id = ".mysql_real_escape_string($showPP_ids));
    }

推荐答案

您在此处没有将值设置为零的内容. $ _POST数组中只会缺少未选中的框.

You have nothing here that sets the values to zero. Boxes that are not checked will simply be absent from the $_POST array.

您需要单独列出所有复选框的名称,并循环遍历所有复选框,并将其与$ _POST数组进行比较.

You'll need to make a separate list of the names of all of the checkboxes and cycle through those, comparing them against the $_POST array.

不会编写任何代码,但是:

Wasn't going to write any code, but:

$allids = array('id1','id2','id3');

foreach ($allids as $oneid) {
  $val = (int) isset($_POST[$oneid]);  // will be 0 or 1
  mysql_query("UPDATE istable SET showPP = $val WHERE id = ".mysql_real_escape_string($oneid));
}

请注意,由于我们知道所有id值都是安全的,因此我们在这里实际上并不需要mysql_real_escape_string,但这是一个好习惯,以防万一有人后来不小心更改$ allids数组.

Note that we don't really need the mysql_real_escape_string here since we know that all the id values are safe, but it's good practice just in case someone comes along later and carelessly changes the $allids array.

再次:假设我们不知道要查找的ID.

Edit again: Suppose we don't know what ids to look for.

mysql_query("UPDATE istable SET showPP = 0");
foreach ($_POST as $oneid=>$nothing) {
  mysql_query("UPDATE istable SET showPP = 1 WHERE id = ".mysql_real_escape_string($oneid));
}

这篇关于PHP/MySQL更新复选框到数据库的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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