简体   繁体   English

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

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

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. 在此表上方,我具有php代码,这些代码可在if isset条件下进行sql查询,以便仅在按表单上的Submit之后才加载。 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 因为在页面加载时它正在尝试在不存在的$ result上执行mysqli_fetch_array

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. 我已经根据您所说的使用了isset($result) 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"]) ). 您可以通过检查count($_POST)或类似方法( 不是检查isset($_POST["submit"]) )的方法来检查isset($_POST["submit"]) If you are fetching for AJAX Response, it is always better to use a different separate file for this. 如果您要获取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