MuhammadCST MuhammadCST - 4 months ago 11
PHP Question

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

I have the following two pieces of

PHP
code, both on the same page, but only the first one runs. What seems to be the problem?

The code:

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>

Answer

First of all, be sure to open and close your HTML tags properly. Then change your code to the following:

<?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>
  • There is absolutely no reason to repeat the same block of PHP code twice when you can execute it just once.
  • You can just initiate two variables outside the conditional statement and then change their values based on the result.
  • Then, you can just echo the variables in the h1 tags you want to respectively.

Side note: For <?= $variable ?> to work in versions < PHP 5.4, the short tags must be enabled in the php.ini file.