首页 > 解决方案 > 使用 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>'; 
    }

标签: javascriptphparraysjson

解决方案


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.


推荐阅读