Php - PostgreSQL将数据回显到一个单元格中(HTML表格)

问题描述 投票:1回答:1

我正在尝试以下面显示的格式回显数据库中的数据;

|column-1|column-2|column-3|column-4|column-5|
|--------|--------|--------|--------|--------|
|My Name |  Date  |Message | People |Phone #s|
                           | People |Phone #s|
                           | People |Phone #s|
                           | People |Phone #s|
                           | People |Phone #s|

这意味着,我从数据库中选择的数据是第4列,第5列中的人从第1列的人那里收到消息(第3列)。但根据我的代码回应数据库中的数据,我在第4列和第5列的每个人都有一个新列,如下所示;

|column-1|column-2|column-3|column-4|column-5|
|--------|--------|--------|--------|--------|
|My Name |  Date  |Message | People |Phone #s|
|My Name |  Date  |Message | People |Phone #s|
|My Name |  Date  |Message | People |Phone #s|
|My Name |  Date  |Message | People |Phone #s|
|My Name |  Date  |Message | People |Phone #s|

下面是我生成表格的php代码;

echo "<table id='table'>";
while($row=pg_fetch_assoc($result)){echo "<tr>";
echo "<td align='left' width='200'>" . $row['message_by'] . "</td>";
echo "<td align='left' width='200'>" . $row['message_date'] . "</td>";
echo "<td align='left' width='200'>" . $row['message_text'] . "</td>";
echo "<td align='left' width='200'>" . $row['phone_number'] . "</td>";
echo "<td align='left' width='200'>" . $row['recipient_name'] . "</td>";
echo "</tr>";}
echo "</table>";

所以问题是如何将第4列和第5列数据输出到单个单元格中,或者将数据回送到不同的单元格而不重复第1列到第3列?

php html-table postgresql-9.1
1个回答
1
投票

处理问题的典型方法是构建一个小型状态机,用于跟踪列值的变化。在您的情况下,似乎如果前三列中的任何值发生更改,则您希望打印完整记录。否则,只需打印最后两列。下面使用的技巧是我们总是向下丢弃5个<td>标签,但对于重复行,我们只将空字符串分配给这些单元格。

$col1 = NULL;
$col2 = NULL;
$col3 = NULL;
echo "<table id='table'>";
while ($row = pg_fetch_assoc($result)) {
    $text1 = '';
    $text2 = '';
    $text3 = '';
    if ($row['message_by'] != $col1 ||
        $row['message_date'] != $col2 ||
        $row['message_text'] != $col3) {
        $col1 = $row['message_by'];
        $col2 = $row['message_date'];
        $col3 = $row['message_text'];
        $text1 = $col1;
        $text2 = $col2;
        $text3 = $col3;
    }
    echo "<tr>";
    echo "<td align='left' width='200'>" . $text1 . "</td>";
    echo "<td align='left' width='200'>" . $text2 . "</td>";
    echo "<td align='left' width='200'>" . $text3 . "</td>";
    echo "<td align='left' width='200'>" . $row['phone_number'] . "</td>";
    echo "<td align='left' width='200'>" . $row['recipient_name'] . "</td>";
    echo "</tr>";
}
echo "</table>";

重要提示:如果您的Postgres查询使用ORDER BY对结果集进行排序,则此答案仅起作用,并且才有意义。特别是,应该排序查询,首先排序三个消息列。

© www.soinside.com 2019 - 2024. All rights reserved.