[英]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.