PHP复选框返回值(选中/未选中)并更新

时间:2018-05-08 19:27:51

标签: php select checkbox sql-update

我有一个提交大量复选框的表单 - 这很好用。

然后我有一个我可以打开的表单,它将显示所述复选框,并将根据运行的SQL查询进行检查或不检查。

SQL查询运行正常回显但我无法将该框显示为已选中。在此之后,我希望能够选中取消选中框并通过SQL进行更新。

<?php
    session_start();
    ini_set('display_errors', 1); error_reporting(-1);
    $data = $_GET['id'];
    require 'connect.php';
    $sql1 = "SELECT id, phone, email, pager
    FROM [dbo].[preference] WHERE id = '$data'";
    $stmt1 = sqlsrv_query($con,$sql1);
    if( $stmt === false) {
    die( print_r( sqlsrv_errors(),true));
}   
        while ($row1 = sqlsrv_fetch_array($stmt1)){
        $id = $row1['id'];
        $phone = $row1['phone'];
        $email = $row1['email'];
        $pager = $row1['pager'];
}
?>


<td><input type="checkbox" name="phone" class="check" value="1">phone</td>
<td><input type="checkbox" name="email" class="check" value="1">email</td>
<td><input type="checkbox" name="pager" class="check" value="1">pager</td>

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

就像在$ phone中说的那样,值已被检查&#39;

你的代码应该是

<td><input type="checkbox" name="phone" class="check" value="1" <?php ($phone == 'checked' ? 'checked' : '') ?>>phone</td>

答案 1 :(得分:0)

我仍然不确定我理解这个问题......

您在更新后加载脚本。渲染反映了当时的当前状态。您提交到脚本,执行更新,然后重新加载...然后呈现更新的状态...

<?php
        ...
        $id = $row1['id'];
        $phone = $row1['phone'];
        $email = $row1['email'];
        $pager = $row1['pager'];
}
?>


<td><input type="checkbox" name="phone" class="check" value="1" <?= (!empty($phone)) ? 'CHECKED' : '' ?>>phone</td>
...

高级......

//pseudo code for a CRUD script...

//is this a POST?
if (isset($_POST['submit')) {
  //validate user input, never trust the user, beware SQL injection...

  //if passes validation update the values in the database

  //if not, raise error flags, re-display the form (you'll see you need to use the supplied POST data, that failed to validate, as the inputs values or you'll lose the provided input, think it will make sense when you het here...)
}

//here could be a POST or initial load... could even flow here to provide confirmation of update and show new values

//load current data from database

//render form based off vurrent values