[英]Displaying query in browser with table
您好,我正在使用一個 sqlite 數據庫,並且我已經用正在運行的 php 編寫了一個查詢。 但是我似乎無法構建一個解決方案來在瀏覽器(表格或其他)中顯示此查詢的結果。 這是我的代碼。 這是該系統的最后一個元素,因此不勝感激。
代碼:
$db = new PDO('sqlite:daypilot.sqlite');
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE end > ? AND start < ?';
$stmt = $db->prepare($sql); $stmt->execute([$start, $end]);
$events = $stmt->fetchAll();
[更新] 從評論中,OP 已經嘗試過
<table>
<tr>
<th>id</th> <th>name</th> <th>contact</th>
</tr>
<?php foreach ($events as $event): ?>
<tr>
<td><?php echo $event['id'] ?></td>
<td><?php echo $event['name'] ?></td>
<td><?php echo $event['contact'] ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
$db = new PDO('sqlite:daypilot.sqlite');
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE end > ? AND start < ?';
$stmt = $db->prepare($sql); $stmt->execute([$start, $end]);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
$table = '<table>';
foreach($events as $event) {
$table .= ' <tr>';
$table .= ' <td>' . $event['column_name'] . '</td>';
// repeat for every column you want to add
$table .= ' </tr>';
}
$table .= '</table>';
echo $table;
?>
好吧,這是構建 HTML 表格的最簡單(但不是最好)的方法。 您應該將該片段代碼插入到您希望表格出現的位置。
我將PDO::FETCH_ASSOC
傳遞給 fetchAll 方法以確保數據作為關聯數組返回,然后您必須迭代它並提取所需的列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.