du8442 2016-05-03 09:39
浏览 12
已采纳

PHP - 如何在if isset条件中嵌入while循环?

I have this table element with the following code:

<?php
if(isset($_POST["submit"])){
    if (strlen($cIdMsg = 0) && strlen($cFirstNameMsg = 0) && strlen($cLastNameMsg = 0) && strlen($pCodeMsg = 0)) {
        require_once("conn.php");
        $sql2 = "SELECT * FROM customer;";
        $results = mysqli_query($conn, $sql2)
        or die ('Problem with query' . mysqli_error($conn));
        echo "no errors found";
    }
}
?>

<table>
<tr>
    <th>Customer ID</th>
    <th>FIrst Name</th>
    <th>Last Name </th>
</tr>

<?php
    while ($row = mysqli_fetch_array($results)) { ?>
    <tr>
        <td><?php echo $row["customerID"]?></td>
        <td><?php echo $row["firstName"]?></td>
        <td><?php echo $row["lastName"]?></td>
    </tr>
<?php } ?>
</table>

Above this table I have the php code that makes the sql queries inside an if isset condition so that it only loads after pressing submit on the form. I would like to do the same to the table. That is to only make it load after pressing submit. because on page load it is trying to do the mysqli_fetch_array on a non existent $result yet

  • 写回答

2条回答 默认 最新

  • dssqq64884 2016-05-03 09:41
    关注

    Wrap the whole table inside:

    <?php if (isset($result)) { ?>
    <table>
    <tr>
        <th>Customer ID</th>
        <th>FIrst Name</th>
        <th>Last Name </th>
    </tr>
    
    <?php
        while ($row = mysqli_fetch_array($results)) { ?>
        <tr>
            <td><?php echo $row["customerID"]?></td>
            <td><?php echo $row["firstName"]?></td>
            <td><?php echo $row["lastName"]?></td>
        </tr>
    <?php } ?>
    </table>
    <?php } ?>
    

    I have used isset($result) based on what you have said. You can check for the POST values by checking for count($_POST), or something similar (not a good idea to check for isset($_POST["submit"])). If you are fetching for AJAX Response, it is always better to use a different separate file for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料