0

I have a while loop fetching data from mysql database and I need to have them save in an html table format which works as per the below code. However instead of 'echoing' the table rows, is there a way to store the final table with all data in a single variable $finalTable so this way i can just echo $finalTable on any pages I need instead of writing the whole while loop each time:

echo '<table>';
while ($row = mysqli_fetch_assoc($resultX)){
    $page_name = $row['page_name'];
    $status = $row['status'];
    echo '<tr>';
    echo '<td>'.$page_name .'</td>';
    echo '<td>'.$status.'</td>';
    echo '</tr>';
}
echo '</table>';
Paul T.
  • 4,703
  • 11
  • 25
  • 29
Avinash
  • 21
  • 7

3 Answers3

1
$finalTable = '<table>';
  while ($row = mysqli_fetch_assoc($resultX)){
    $page_name = $row['page_name'];
    $status = $row['status'];
    $finalTable .= '<tr>';
    $finalTable .= '<td>'.$page_name .'</td>';
    $finalTable .= '<td>'.$status.'</td>';
    $finalTable .= '</tr>';
}
$finalTable .= '</table>'

using .= concatenates your all data to a single variable. Now you can print $finalTable to print your table

Rohit Sahu
  • 284
  • 5
  • 15
1

if your point is to create a html string you can simply instead of echoing that, create a string and concatenate your table items to it

$finalTable ='<table>';
while ($row = mysqli_fetch_assoc($resultX)){
    $page_name = $row['page_name'];
    $status = $row['status'];
    $finalTable .= '<tr>';
    $finalTable .= '<td>'.$page_name .'</td>';
    $finalTable .= '<td>'.$status.'</td>';
    $finalTable .= '</tr>';
}
$finalTable.= '</table>'
//use this variable everywhere you wish
echo $finalTable;

$a .= "x" mean's assign value of $x to anything it have before plus "x". this is simplified version of this $a = $a . "x"

if you don't want to change your code structure istead of above code you can capture php output buffer that already discussed here this will capture output(at this time the point is echo) into a string instead of write directly into client's browser

ob_start();
//your own code
echo '<table>';
while ($row = mysqli_fetch_assoc($resultX)){
    $page_name = $row['page_name'];
    $status = $row['status'];
    echo '<tr>';
    echo '<td>'.$page_name .'</td>';
    echo '<td>'.$status.'</td>';
    echo '</tr>';
}
echo '</table>';
//save it in string variable
$htmlTableData = ob_get_clean();
//echo this one every where you wish
echo $htmlTableData;
1

Sure. You can pass table to the variable:

$finalTable = '<table>';
while ($row = mysqli_fetch_assoc($resultX)){
    $finalTable.='<tr><td>'.$row['page_name'] .'</td><td>'.$row['status'].'</td></tr>';
}
$finalTable .= '</table>';
Jsowa
  • 9,104
  • 5
  • 56
  • 60