将多个查询数据转换为单个HTML表(PHP,MySQL)

时间:2010-08-31 21:51:03

标签: php mysql

这是我目前的代码。我正在尝试将来自三个单独查询的数据显示到具有多个列的单个表中。我的时间陈述在这里错了吗?它打印1个表数据,然后打印一个表格数据,而不是在同一行中打印它。

echo "<table border='1'>
<tr>
<TH COLSPAN=2>July 2010</TH>
<TH COLSPAN=2>August 2010</TH>
<TH COLSPAN=2>September 2010</TH>
</tr>
<tr>
<th>User</th>
<th>Posts</th>
<th>User</th>
<th>Posts</th>
<th>User</th>
<th>Posts</th>
</tr>";

while (($row = mysql_fetch_assoc($july)) || ($row2 = mysql_fetch_assoc($aug)) || ($row3 = mysql_fetch_assoc($sept))) {
echo "<tr>";
echo "<td>" . $row['cUsername'] . "</td>";
echo "<td>" . $row['postCount'] . "</td>";
echo "<td>" . $row2['cUsername'] . "</td>";
echo "<td>" . $row2['postCount'] . "</td>";
echo "<td>" . $row3['cUsername'] . "</td>";
echo "<td>" . $row3['postCount'] . "</td>";
echo "</tr>";
}

echo "</table>";

3 个答案:

答案 0 :(得分:2)

while循环正在使用OR子句。这意味着如果第一个返回true,它将不会执行第二个。

答案 1 :(得分:2)

$data = array();

while($row = mysql_fetch_assoc($july)) {$data['row'][] = $row;}
while($row = mysql_fetch_assoc($aug))  {$data['row2'][] = $row;}
while($row = mysql_fetch_assoc($sept)) {$data['row3'][] = $row;}

$count = count($data['row']);

for($i=0;$i<=$count;$i++)
{
    echo '<tr>';
        if(($i % 3) == 1)
        {
            echo "<td>" . $data['row3'][$i]['cUsername'] . "</td>";
            echo "<td>" . $data['row3'][$i]['postCount'] . "</td>";
        }else if(($i % 2) == 1)
        {
            echo "<td>" . $data['row2'][$i]['cUsername'] . "</td>";
            echo "<td>" . $data['row2'][$i]['postCount'] . "</td>";
        }else /*Never try find remainder of 1 as theres always a multiple of 1*/
        {
            echo "<td>" . $data['row'][$i]['cUsername'] . "</td>";
            echo "<td>" . $data['row'][$i]['postCount'] . "</td>";
        }
    echo '</tr>';
}

通过将结果单独提取到本地数组而不是尝试同时获取3个不同的行,您应该单独执行它们并将它们存储在局部变量中,只需在单词之后取消设置变量(如果它是一个大数组)。 / p>

我的代码是未经测试的。

答案 2 :(得分:0)

这将需要打开三个单独的连接到MySQLaт,运行三个查询,每个查询都有自己的连接。

您最好将此查询重写为

SELECT  user_id,
        (
        SELECT  COUNT(*)
        FROM    posts p
        WHERE   p.user_id = u.user_id
                AND p.date >= '2010-06-01'
                AND p.date < '2010-07-01'
        ) AS june_count,
        (
        SELECT  COUNT(*)
        FROM    posts p
        WHERE   p.user_id = u.user_id
                AND p.date >= '2010-07-01'
                AND p.date < '2010-08-01'
        ) AS july_count,
        (
        SELECT  COUNT(*)
        FROM    posts p
        WHERE   p.user_id = u.user_id
                AND p.date >= '2010-08-01'
                AND p.date < '2010-09-01'
        ) AS aug_count
FROM    users u