douren1891 2019-03-27 00:25
浏览 204

在PHP中嵌套循环和语句

I have this code and I want to add checkbox according to fetched number from database with PHP and when clicked on checkbox update a field in db with JQuery, this work for 1 checkbox but this cant work for more checkbox and Also my PHP loop does not work how i can add checkbox with loops and when user click on any checkbox update His own field on database, anybody can resolve my problem ?

My JQuery code:

$(document).ready(function () {
    $('#mycheckbox').change(function () {
        var returnVal = ("Are " + "you sure?");
        if (returnVal) {
            postToServer($(this).prop("checked"));

        } else {
            $(this).prop("checked", !$(this).is(":checked"));
        }
    });
    function postToServer(state) {
        let value = (state) ? 1 : 0;

        $.ajax({
            type: 'POST',
            url: 'checkbox.php',
            data: {'value': +value},
            success: function (response) {
                //handle response
            }
        });
    }
}

and my PHP code:

$sql1="SELECT * FROM `users` ";
$result1= mysqli_query($conn,$sql1);
$row1=mysqli_fetch_assoc($result1);
$lights=$row1["lights"];
for ($i=0; $i < $lights; $i++){
    if ($row["value"]=='1'){
        echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" checked=\"checked\">";
    } else {
        echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" >";
    }
}
  • 写回答

2条回答 默认 最新

  • duanshan3065 2019-03-27 02:34
    关注

    This should fix the issue with your loop not running and should print out the checkbox for each user

    $users= mysqli_query($conn, "SELECT * FROM user");
    while($row = mysqli_fetch_assoc($users)) {
        if ($row["value"]=='1'){
           echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" checked="checked">';
        }else {
            echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" >';
        }
    }
    

    Added the id of the user to each checkbox id in order to make each one have a unique id

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题