繁体   English   中英

PHP-如何在ifset条件中嵌套while循环?

[英]PHP - How can I nest a while loop inside an if isset condition?

我有这个表元素,其代码如下:

<?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>

在此表上方,我具有php代码,这些代码可在if isset条件下进行sql查询,以便仅在按表单上的Submit之后才加载。 我想在桌子上做同样的事情。 也就是说,只有在按提交后才加载它。 因为在页面加载时它正在尝试在不存在的$ result上执行mysqli_fetch_array

将整个表格包装在里面:

<?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 } ?>

我已经根据您所说的使用了isset($result) 您可以通过检查count($_POST)或类似方法( 不是检查isset($_POST["submit"]) )的方法来检查isset($_POST["submit"]) 如果您要获取AJAX响应,则最好为此使用另一个单独的文件

<?php if(mysqli_num_rows($result)!=0) { ?>
<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 } ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM