php - 如果值匹配,则选中复选框并在提交时使用复选框值更新数据库

标签 php jquery mysql

我正在尝试如果值在数据库中显示复选框已选中。我检查了不同的值并单击提交按钮更新数据库,其中更新值是复选框选中的值。

这是我的代码:

    <?php
    include "database_connection.php"; 
    $cutomername = $_GET['username'];
    $productid = $_GET['userid'];
    $cust_id = $_GET['custid'];
    $productid_arr = explode(',' , $productid);
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> <?php echo $cutomername;?></title>
    </head>

    <body>

    <form method="post" name="checkboxForm">
    <?php

    $query_flags = "select * from products";
    $row_flags=mysql_query($query_flags); 
    $i=0;

    while ($row = mysql_fetch_array($row_flags)){

           $product_id = $row['product_id'];
           $product= $row['product'];
           if($productid_arr[$i] ==$row['product_id']) 
           {
              $check = 'checked="checked"';
           } else{
              $check = '';
           }
           if(in_array($row['product_id'], $chvalues))
           {
              echo  "<input   type=\"checkbox\" name=\"checkbox[]\"  id=\"$product_id\" value='" . $row['product_id'] . "' $check />";
           } else{
              echo  "<input  type=\"checkbox\" name=\"checkbox[]\"  id=\"$product_id\" value='" . $row['product_id'] . "' $check/>";
           }
    echo $row['product'];
    echo "<hr />"; 
    $i++;
    }   
    ?>  
    <input class="submit" type="submit" value="Submit" name="submit">   

    <?php
    $chvalues = array();
    if(isset($_POST['checkbox']))
    {
       foreach($_POST['checkbox'] as $ch => $value)
       {
       $chvalues[] = $value;
       }
    }

    $des_prod_id = implode(',' , $chvalues);
    $query = mysql_query("UPDATE customer SET product_id = '$des_prod_id'  where  ID = '$cust_id'");
   ?>

</form>
</body>
</html>

最佳答案

改变这一行:

 $query = mysql_query("UPDATE customer SET product_id = $products where  customer_name = $cutomername");

到:

$query = mysql_query("UPDATE customer SET product_id = $value where  customer_name = $cutomername");

$products 应该是 $value,因为您在 foreach 循环中迭代并将每个元素分配给此变量。

关于php - 如果值匹配,则选中复选框并在提交时使用复选框值更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700065/

相关文章:

php - 表单数据未插入数据库

javascript - Tablesorter 将不会显示可排序的标题

php - 查找用户的哪些推文被收藏

php - 无效参数编号 : number of bound variables does not match number of tokens in Doctrine

javascript - jquery ui 添加不必要的代码和破坏东西

jquery - "Unserialize"这个字符串 : %C3%A9%C3%A0%C3%A9%C3%A0

php - 帮助 MySql 触发器或替代

javascript - 捕获网页上的签名(通过平板电脑屏幕)

javascript - backbone.js - 事件只触发一次

MySQL If else 构造语法