javascript - 使用 PHP 在列中显示 JSON 数据,然后以相同的格式返回选择
问题描述
我目前正在编写机票预订脚本(包括日期、预订时间和可用数量)。
我正在尝试与一个 API 通信,该 API 应该以 JSON 格式从数据库向我发送数据,以便我可以解释它并在 PHP 中显示在我应该在列标题中显示日期的列中,每个单元格中的小时数和默认数量(在我的示例中,我们从 60/60 开始,在选择用户时将减 1。
目前,我只是想设法为每个日期自动创建一个列,其中包含要选择的值和剩余数量的值(知道选择减 1)然后以 JSON 格式返回结果到 API 以更新数据库并通过将用户的 IP 分配给它来保存选择。
我开始了一个小脚本,它以 JSON 格式检索数据库的元素作为示例,我想我必须创建一个 foreach 循环来创建我的列,但我现在卡住了。感谢您提供的线索或您认为可以带给我的任何帮助。
这是我正在尝试做的事情的图片:
<?php
try{
$pdo=new PDO(
'mysql:host=localhost;dbname=date_booking',
'root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch(PDOException $e){
echo $e->getMessage();
}
$statement=$pdo->prepare("SELECT * FROM tbl_booking");
$statement->execute();
$datas = array();
while($res=$statement->fetch(PDO::FETCH_ASSOC)) {
$datas[]=$res;
}
$someArray = $datas; // Replace ... with your PHP Array
foreach ($someArray as $key => $value) {
echo '<pre>';
echo $value["date_booking"]. ' | ' . $value["hour_booking"]. ' | ' . $value["nb_booking"];
echo '</pre>';
}
解决方案
Start by selecting ONLY what you want from the table, then you can simply use fetchAll()
to return the complete resultset as an array of arrays or objects, I used Objects in the below example.
It is then simple to make that into a JSON String to return to the caller using json_encode()
<?php
try{
$pdo=new PDO(
'mysql:host=localhost;dbname=date_booking',
'root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch(PDOException $e){
echo $e->getMessage();
}
$statement=$pdo->prepare("SELECT date_booking, hour_booking, nb_booking
FROM tbl_booking");
$statement->execute();
$rows = $statement->fetchAll(PDO::FETCH_OBJ);
echo json_encode($rows);
Then in you javascript you have an array of objects that you can place into your page however you want.
推荐阅读
- core-data - Swift4 Core Data如何按日期插入NSOrderedSet?
- python - Pytorch:结合自动和手动方法
- jquery - Jquery 不适用于 DOM 更改
- terminal - 通过 kill 优雅地杀死 rosbag
- eclipse - 在 Eclipse 中,一种无需移动鼠标即可查看代码错误的方法?
- javascript - 在特定包含的 php 文件中加载 js 文件
- docker - Docker Swarm - 一些任务容器在部署时没有更新
- typescript - Typescript:在另一个类上扩展泛型类型的泛型类型
- python - 如何避免在打印出字典的末尾打印逗号?
- c - 当 double 值超出 char 范围时,C 中的 Double 到 char 转换规则