我有以下两段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
文件中启用短标记。