user5779223 user5779223 - 6 months ago 15
HTML Question

How to echo a table in two piece separated code in PHP?

Now I wish to construct a list of tables under nested

while
loop and
if-else
condition with PHP, the format of the code is as below:

while(){
if (){
..... // extract the data
while(){

construct a table using the data extracted above
}
}
elseif (){
..... // extract the data
while(){

construct a table using the data extracted above
}
}
}


Specifically, in the inner while loop the code is:

while ( $chat = mysqli_fetch_assoc($chatQ))
{
echo
"<table class='table table-hover' >"
."<td>"
.$conver['sender_name']."\t".$chat['sender']."\t".$chat['send_time']."\t".$chat['content']
."</td>"
."<td>"
."<form id='join' action='group_chat.php' method ='POST' accept-charset='UTF-8'>"
// post the group id
."<input type='hidden' name='group_id' id='group_id' value=".$conver['sender_id']."/>"
."<button class='btn btn-default' type='submit'>Enter</button>"
."</form>"
."</td>"
."</table>";
}


But the result is very ugly:
enter image description here

The problem is that the
Enter
button is associated with each message. But what I want is that after displaying all the messages, there is a
Enter
button which can direct to the specific group. But I don't know how to separate the code. Could you please do me a favor? Thanks in advance!

Answer

You can do something like this:

<?php
$counter = 0;
echo '
<form>
    <table>';
while ( $chat = mysqli_fetch_assoc($chatQ)){
    $counter++;
    echo '
        <tr>
            <td>
                group_id_'.$counter.'
            </td>
            <td>
                <input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
            </td>
        </tr>';
}
    echo '
        <tr>
            <td colspan="2">
                <button type="submit">Enter</button>
            </td>
        </tr>
    </table>
</form>';   
?>

Also you dont have to limit yourself to echo everything in order by setting variables. See example below:

<?php
$counter = 0;
$data = NULL;
while ( $chat = mysqli_fetch_assoc($chatQ)){
    $counter++;
    $data .='
        <tr>
            <td>
                group_id_'.$counter.'
            </td>
            <td>
                <input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
            </td>
        </tr>';
}
    echo '
<form>
    <table>'.$data.'
        <tr>
            <td colspan="2">
                <button type="submit">Enter</button>
            </td>
        </tr>
    </table>
</form>';   
?>