簡體   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