[英]PHP dynamic HTML table using SQL
我使用下面的代碼基於SQL結果生成HTML表。
碼
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT orders.order_no, orders.porder_no, orders.date, order_totals.value
FROM orders, order_totals
WHERE orders.order_no = order_totals.order_no
AND orders.account_no = '" . $_SESSION['session_account'] . "'
ORDER BY orders.order_no DESC
)
WHERE ROWNUM <= 15
");
oci_execute($stid);
echo "<table class='table'>
<thread>
<tr>
<th>Order No</th>
<th>Purchase Order No</th>
<th>Date</th>
<th>Value</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td><a href="view.php?id=' . $row['0'] . '">' . $row['0'] . '</a></td>';
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
是否可以使代碼中的HTML表生成部分更加動態,以便例如在我需要添加其他列的情況下,可以在代碼中添加SQL部分?
我有一個想法,設置使用的列標題AS
在SQL,我可以修改使用SQL AS
展現真實的列標題我想例如
SELECT orders.order_no AS "Order No"
, orders.porder_no AS "Purchase Order No"
, orders.date AS "Date"
, order_totals.value AS "Total"
但是HTML表部分呢,有沒有一種方法可以動態地打印所有列和行,例如創建一個可以處理任何表的printTable
函數?
$ row var是一個數組,因此您也可以對其進行循環。 由於您要對待第一個字段,因此請在循環之前將其寫出,並從1開始循環。
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td><a href="view.php?id=' . $row[0] . '">' . $row[0] . '</a></td>';
for ( $ii = 1; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
我不知道unset($ row)的用途,所以我省略了它。
您可以使用:
SELECT * FROM {TABLENAME}
然后獲取一個數組。 您可以使用$row['{FIELDNAME}']
獲取數據
您可以使用雙循環:
$results = $PDO->fetchAll(PDO::FETCH_ASSOC); // here is all columns and rows from db query.
echo '<table><tr>';
// loop only first row to get header
foreach ($results[0] as $header => $value) {
echo "<th>{$header}</th>"
}
echo '</tr>';
// loop all rows
foreach ($results as $row) {
echo '<tr>';
// and loop any number of columns
foreach ($row as $cellName => $cell) {
// If you have only one special case, than use if statement
switch ($cellName) {
case 'order_no':
echo "<td><a href='http://example.com/getOrder?id={$cell}'>{$cell}</a></td>";
break;
default: echo "<td>{$cell}</td>";
}
}
echo '</tr>';
}
echo '</table>';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.