【问题标题】:PHP - How can I nest a while loop inside an if isset condition?PHP - 如何在 if isset 条件中嵌套 while 循环?
【发布时间】:2016-08-28 07:03:09
【问题描述】:

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

<?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 查询,以便它仅在按表单上的提交后加载。我想对桌子做同样的事情。那就是只有在按下提交后才加载。因为在页面加载时它试图在一个不存在的 $result 上执行 mysqli_fetch_array

【问题讨论】:

  • 发布你的完整代码!!
  • 您想使用 Ajax 请求在后台获取数据并仅在获得查询结果时插入行?

标签: php forms mysqli


【解决方案1】:

将整个表格包裹在里面:

<?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) 或类似的东西来检查 POST 值(检查 isset($_POST["submit"]) 不是一个好主意)。如果您要获取 AJAX 响应,最好为此使用不同的单独文件

【讨论】:

  • 谢谢你这工作完美。请问为什么不推荐使用 isset($_POST["submit"]),因为我们被告知要使用它来回发
  • @nanjero05 一些愚蠢的浏览器不会发送Submit 值,还有许多开发人员,忘记命名Submit 按钮。以防万一。 :)
【解决方案2】:
<?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 } ?>

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2013-05-11
    • 2016-10-30
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多