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条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测