我想从一个SQL查询中打印出“多个表”。逻辑是每次打印一行具有不同于上一行值的新值,以创建HTML新表。
也许是这样
This stuff is Assigned to JOE
-----------------------------------
Assigned to |Column1 |Column2
-----------------------------------
Joe |1 |A
Joe |2 |B
Joe |3 |C
This stuff is Assigned to Adam
-----------------------------------
Assigned to |Column1 |Column2
-----------------------------------
Adam |1 |A
Adam |2 |B
This stuff is Assigned to Patrick
-----------------------------------
Assigned to |Column1 |Column2
-----------------------------------
Patrick |1 |A
Patrick |2 |B
Patrick |3 |C
我对我的代码进行了测试运行,这是一个基本的PHP If-Statement,它试图检测上一行的变量是否未更改。如果可以,则插入一些代码。
$tsql = "
SELECT
id
AssignedTo
Column1
Column2
FROM somewhere
ORDER BY AssignedTo ASC";
/* Execute the query. */
$stmt = sqlsrv_query( $conn, $tsql);
/* I will set this variable to whatever for now */
$AssignedTo = '';
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
If ($AssignedTo != $row[1])
{
$AssignedTo = $row[1];
echo "<h1>This is assigned to ".$AssignedTo."</h1>";
echo "<table><tr>headings</tr>";
}
echo "<tr>bla bla</tr>";
}
但是结果却是这样的:
This stuff is Assigned to JOE
--------------------------------
This stuff is Assigned to Adam
--------------------------------
This stuff is Assigned to Patrick
--------------------------------
//Rest of the Rows down here after
即使 if语句在内之内,我也不明白为什么我的“东西分配给”为什么在所有其余表行上循环显示>。
谢谢
答案 0 :(得分:1)
启动表格后,您再也没有关闭过表格。
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
If ($AssignedTo != $row[1])
{
if ($AssignedTo != '') {
echo '</table>';
}
$AssignedTo = $row[1];
echo "<h1>This is assigned to ".$AssignedTo."</h1>";
echo "<table><tr>headings</tr>";
}
echo "<tr>bla bla</tr>";
}