如何选择多个复选框并在db中更新

时间:2016-07-29 14:22:29

标签: php html ajax

我有一个表单,对于我在页面上显示的每一行。它还存在一个每个项目的复选框,当我点击它时,如果它未被选中,它将被检查并保存在db值1或值0否则。但我想知道如何选择多个未选中的复选框并在我的数据库中更新所有复选框,而不是一对一地使用它们。有任何建议怎么做?

   $displayChecked = $row['publish'] == 1 ? 'checked' : '';
   $check = $row['publish'] == 1 ? 'true' : 'false';
   (...)
  <?php if ($check == "true") {echo "Publish";} else {echo "Unpublished";}?> 
   <input type="checkbox"  name="check" value = "<?php echo  $check; ?>" <?php echo $displayChecked; ?> OnClick="doAction(<?php echo $check;?>, <?php echo $id;?>);" > 

doAction:

 function doAction(check,id){
 $.ajax({

      type: "GET",
      url: "file.php",
      data: "check=" + check + "&id=" + id,
      success: function(msg){
                 alert( "Data Saved: " + msg );
               }
 });
 }

file.php

 <?php 
 require_once("connectionfile.php");

        $id = $_GET['id'];
        $check = $_GET['check'];
        if ($check == "false"){
            $query = mysql_query("update article set publish = 1 where id =" . $id);

            echo "Published";
        }
        else {
            $query = mysql_query("update article set publish = 0 where id =" . $id);
            echo "Unpublished";
        }

 ?>

3 个答案:

答案 0 :(得分:0)

而不是单个id,将当前已检查的id数组传递给doAction,并在file.php中循环它们。

答案 1 :(得分:0)

您可以构造一个包含所有检查状态的字符串和另一个包含所有ID的字符串。让我们创建新功能&#34; saveAll&#34; :

function saveAll () {   // ◄■■■■■ PARAMETERS UNNECESSARY.
// CONSTRUCT STRINGS WITH CHECKS AND IDS OF ALL THE CHECKBOXES.
  var checkboxes = $("[name=check]"); // ARRAY OF CHECKBOXES NAMED "CHECK".
  var checks = ""; // EXAMPLE : "0,1,1,0,0," (COMMA SEPARATED).
  var ids = ""; // EXAMPLE : "2,14,21,33,40," (COMMA SEPARATED).
  for ( i = 0; i < checkboxes.length; i++ )
  { checks += ( checkboxes[ i ].checked ) ? "1," : "0,"; // COMMA SEPARATED.
    ids += checkboxes[ i ].id + ","; // COMMA SEPARATED.
  }
 $.ajax({
      type: "GET",
      url: "save_all.php",  // ◄■■■■■ NEW PHP CODE.
      data: "checks=" + checks + "&ids=" + ids,  // ◄■■■■■ PLURAL VARIABLES.
      success: function(msg){
                 alert( "Data Saved: " + msg );
               }
 });
 }

现在,您正在显示带有ID作为&#34; doAction&#34;的参数的复选框:

   <input type="checkbox"  name="check" value = "<?php echo  $check; ?>"
          <?php echo $displayChecked; ?>
          OnClick="doAction(<?php echo $check;?>, <?php echo $id;?>);" >   ◄■■■■■

注意新功能&#34; saveAll&#34;要求复选框具有&#34; name&#34;和&#34; id&#34;,所以让我们改变一下前一段代码:

   <input type="checkbox"  name="check" value = "<?php echo  $check; ?>"
          <?php echo $displayChecked; ?>   id="<?php echo $id;?>"  ◄■■■■■
          OnClick="doAction(<?php echo $check;?>, <?php echo $id;?>);" > 

现在新功能&#34; saveAll&#34;可以获取所有复选框的所有检查状态,用它们构造字符串并将它们发送到新的PHP代码&#34; save_all.php&#34;,如下所示:

<?php
if ( isset( $_GET["checks"] ) && isset( $_GET["ids"] ) )
   { $checks = explode( ",", $_GET["checks"] ); // IGNORE LAST ITEM.
     $ids    = explode( ",", $_GET["ids"]    ); // IGNORE LAST ITEM.
     for ( $i = 0; $i < (count( $ids )-1); $i++ )
        $query = mysql_query("update article set publish=" .
                             $checks[$i] . " where id=" . $ids[$i] );
   }
?>

$checks$ids是数组。我们必须忽略每个数组的最后一个元素,因为字符串以逗号结尾,所以最后一项是空的。

现在,您只需要一个按钮即可使一切正常运行:

<button onclick="saveAll()">Save all</button>

答案 2 :(得分:0)

您应避免使用mysql_*函数,因为它们已从PHP 5.5.x弃用,并且将为removed in the future

我真的建议转向PDO,因为它更多是OOP,或者如果您更喜欢旧的程序方式,那么mysqli就是可行的方法。

现在,据说:

让我们从html / javascript部分开始:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title be here</title>

    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
</head>
<body>
    <form action="" method="post" id="_form">
        <div class="row">
            <?php for($i = 1; $i <= 10; $i++):?>
            <label for="id_<?php echo $i; ?>">Checkbox <?php echo $i; ?></label>
            <input type="checkbox" id="id_<?php echo $i; ?>" name="ids[<?php echo $i; ?>]"><!-- here we assume $i is $id -->
            <br />
            <?php endfor; ?>
            <input type="submit" value="Submit" name="submit" id="_submit">
        </div>
    </form>


    <script type="text/javascript">
        $(document).ready(function(){

            $('#_submit').on('click', function(e){
                e.preventDefault();

                $.ajax({
                    type: "post",
                    url: "file.php",
                    data: $('#_form').serialize(),
                    success: function(data){
                        if(data.success == true){
                            // do stuff here
                        }else{
                            // do other stuff here
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

让我们继续PHP部分:

<?php

if(isset($_POST['ids']))
{
    $input = $_POST['ids'];

    // Lets take care of the query here

    $query = ' UPDATE `article` SET `publish` = CASE';

    foreach($input as $key => $value)
    {
        $query .= ' WHEN `id` = ' . /* typecast to int just in case */ (int) $key . ' THEN ';
        if($value == 'on')
        {
            $query .= '1';
        }
        else
        {
            $query .= '0';
        }
    }

    $query .= ' END WHERE `id` IN (' . implode(',', array_keys($input)) . ')';

    // update stuff using the database handler here

    // return a json response here or just echo out whatever you need
}
else
{
    // return a response here
}

请注意,我已将name="ids[<?php echo $i; ?>]"作为数组放置。 Php实际上将其解释为数组,它将如下所示:

Array
(
    [2] => on
    [4] => on
    [5] => on
    [6] => on
    [7] => on
    [8] => on
)

请注意,密钥不是随机的,它们是我们的ID。

但是,您还会注意到缺少某些ID,即没有选中复选框的ID。那将是一个问题。一个简单的解决方法是执行以下操作:

<input type="hidden" name="ids[<?php echo $i; ?>]" value="off">
<!-- Add a hidden filed with the exact same id BUT with off as a value -->
<!-- In case the user checks the checkbox, then it will overwrite the hidden field -->
<!-- The order of the fields in very important here. Hidden field MUST come first -->

<input type="checkbox" id="id_<?php echo $i; ?>" name="ids[<?php echo $i; ?>]"><!-- here we assume $i is $id -->

所以现在我们的数组看起来像这样:

Array
(
    [1] => off
    [2] => off
    [3] => off
    [4] => off
    [5] => on
    [6] => off
    [7] => off
    [8] => on
    [9] => off
    [10] => off
)

从那以后,构建查询和更新表就很简单了。

查询将如下所示:

UPDATE `article` SET `publish` = CASE WHEN `id` = 4 THEN 1 WHEN `id` = 5 THEN 1 WHEN `id` = 6 THEN 1 END WHERE `id` IN (4,5,6)

这将允许您一次性更新所有记录,而无需循环结果,也不必强制为每个复选框执行一个查询。

对于作为用户体验的前端部分,我认为您可以在更新完成并成功时简单地闪烁警报,否则只显示错误。