代码之家  ›  专栏  ›  技术社区  ›  Rogersj

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

  •  -1
  • Rogersj  · 技术社区  · 7 年前

    我有一个表单,它提交了一大堆复选框-这很好用。

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

    SQL查询使用echo运行正常,但我无法使该框显示为选中状态。在此之后,我希望能够取消复选框并通过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 回复  |  直到 7 年前
        1
  •  0
  •   ficuscr    7 年前

    我还是不太确定我是否理解这个问题。。。

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

    <?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
    
        2
  •  0
  •   Zia Ur Rehman    7 年前

    比如说在$phone中,值要么是“checked”

    您的代码应该是

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