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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算