在带有表格的浏览器中显示查询 [英] Displaying query in browser with table

查看:24
本文介绍了在带有表格的浏览器中显示查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用 sqlite 数据库,并且我在正在运行的 php 中编写了一个查询.但是,我似乎无法构建将在浏览器(表格或其他)中显示此查询结果的解决方案.这是我的代码.这是该系统的最后一个元素,因此感谢您的帮助.

Hi there i am using a sqlite database and i have written a query in php that is running. However i cant seem to build a solution that will display the results of this query in the browser (tabular or other). Here is my code. This is the last element of this system so help is appreciated.

代码:

$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 已经尝试过


[Update] From comment, OP has tried

<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 表格的最简单(但不是最好)的方法.您应该在您希望表格出现的位置插入该片段代码.

Well, this is the simplest (and not the best) way to build the HTML table. You should insert that snippet code in the place where you want the table appears.

我将 PDO::FETCH_ASSOC 传递给 fetchAll 方法以确保数据作为关联数组返回,然后您必须对其进行迭代并提取所需的列

I passed PDO::FETCH_ASSOC to fetchAll method to ensure that the data are returned as associative array, then you have to iterate over it and extract the desired columns

这篇关于在带有表格的浏览器中显示查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆