如何在PHP中用两段分隔的代码回显表?

时间:2016-05-20 19:58:48

标签: php html

现在我希望用PHP构建嵌套while循环和if-else条件下的表列表,代码格式如下:

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
       }
   }
}

具体来说,在内部while循环中,代码是:

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>";
        }

但结果非常难看: enter image description here

问题是Enter按钮与每条消息相关联。但我想要的是,在显示所有消息后,有一个Enter按钮可以指向特定的组。但我不知道如何分离代码。你能帮我一个忙吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以这样做:

<?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>';   
?>

此外,您不必通过设置变量来限制自己按顺序回显所有内容。见下面的例子:

#dup