Home > Back-end >  Nested PHP blocks in HTML
Nested PHP blocks in HTML

Time:11-23

I have a table with 10 rows and 19 columns in MySQL. I am trying to display the content of table in HTML. I wrote the code below for this purpose.

<?php
.
.
.
$con = mysqli_connect($host,$user,$password,$db);
$i="select * from data where user='".$usr."'";
$result=mysqli_query($con,$i);
$matrix = mysqli_fetch_all($result);
        
            
        $row = $matrix[0];
        
        $cell = $row[1];
        echo $cell;
    }

?>

<html>
        <style>
        table {
          border:2px solid black;
          width: 100%;
          margin-left:0%;
        }
        tr, td {
          border:1px solid black;
          width: 1%;
          font-size: 20px;
          text-align:center;
        }
        </style>

        <table>
            <?php
                $b=0;
                while ($b<10) {
                    echo '
                        <tr>
                             <?php
                                $a=0;
                                while ($a<18) {
                                    echo "
                                        <td>
                                            $row[$a]
                                        </td>
                                    ";
                                    $a  ;
                                }
                             ?>
                        </tr>
                    ';
                    $b  ;
                }
            ?>
        </table>
</html>

The code does not work. I also read a similar question that was answered to replace inner <?p ?> with ". ." . I tried this but did not get the expected result. What is wrong with this code?

CodePudding user response:

You are putting an open php tag inside of an echo. Instead, keep them separate.

<table>
<?php
  $b=0;
  while ($b<10) {
    echo '<tr>';
    $a=0;
    while ($a<18) {
      echo "<td>$row[$a]</td>";
      $a  ;
    }
    echo '</tr>';
  $b  ;
  }?>
</table>

In your code, you have this:

...
echo '
  <tr>
     <?php
         $a=0;
         ...

... which has 3 errors. First, anything inside of single quotes in php will not be evaluated (parsed). So, even something like this: echo 'hello $name'; will spit out the output: hello $name whereas echo "hello $name"; (double quotes) will parse the variable $name and will spit out somethign like: hello Sam.

Second, you are trying to open a new php tag when you're already inside a php tag.

Third, and this is really the deal breaker here, you are trying to start a new block of logic ( a loop) inside of an echoed string. This would not work with either single or double quotes. If you look at my answer, I close out the first echo in order to begin the loop.

  • Related