我在一页中有两个PHP代码块,但只有第一个运行


I have this two PHP code blocks in one page, but only the first one runs

我有以下两段PHP代码,都在同一页面上,但只有第一段运行。似乎有什么问题?

代码:

div class="row" >
  <div class="col-md-12">
  enter code here
  <h1 id="username" style="color:white;text-align:center" >
    <?php
    if ($result->num_rows > 0){
  $row = $result->fetch_assoc();
   echo $row["username"];}
    ?>
    </h1>
</div>
</div>

<div class="row">
<div class="col-md-12">
    <h1 id="bash" style="color:blue;text-align:center">
    <?php
if ($result->num_rows > 0){
  $row = $result->fetch_assoc();
   echo $row["bash"];}
    ?>
    </h1>
</div>
</div>

首先,请务必正确打开和关闭 HTML 标记。然后将代码更改为以下内容:

<?php
    $username = null;
    $bash = null;
    if ($result -> num_rows > 0) {
        $row = $result->fetch_assoc();
        $username = $row["username"];
        $bash = $row["bash"];
    }
?>

<div class = "row" >
    <div class = "col-md-12">
        enter code here
        <h1 id = "username" style = "color:white; text-align:center">
            <?= $username ?> <!-- OR --> <?php echo $username; ?>
        </h1>
    </div>
</div>

<div class = "row">
    <div class = "col-md-12">
        <h1 id = "bash" style = "color:blue; text-align:center">
            <?= $bash ?> <!-- OR --> <?php echo $bash; ?>
        </h1>
    </div>
</div>
  • 同一块PHP代码可以只执行一次时,绝对没有理由重复两次。
  • 您可以在条件语句之外启动两个变量,然后根据结果更改它们的值。
  • 然后,您可以分别回显所需的h1标签中的变量

旁注:要使<?= $variable ?>PHP 5.4 <</strong>版本中工作,必须在php.ini文件中启用短标记