使用json的表中的PDO表

时间:2017-03-06 18:14:00

标签: php json pdo

我想使用json

在我的MySQL(PDO)中发送3个表

我的桌子:

$stmt1 = $db->prepare("SELECT * FROM data WHERE id='1'");
$stmt1->execute();
$result1 = $stmt1->fetch(PDO::FETCH_ASSOC);

$stmt2 = $db->prepare("SELECT * FROM weeks WHERE id='2'");
$stmt2->execute();
$result2 = $stmt2->fetch(PDO::FETCH_ASSOC);

$stmt3 = $db->prepare("SELECT * FROM user WHERE id='1'");
$stmt3->execute();
$result3 = $stmt3->fetch(PDO::FETCH_ASSOC);

询问如何将其发送到格式

{"data":[{
                   "title":"name of module2",
                   "description":"description of module2",
                   "weeks":[{"id":2, "title":"Week 02"}],
                   "user":[{"id":2, "name":"john"}],
}]}

1 个答案:

答案 0 :(得分:1)

首先从PDO返回对象,这就是你想要的。

然后只从表中选择您实际需要的列

然后从返回的数据中构建您认为想要的数据结构

python /home/forge/rkim-web-app/database/backup_mysql.py

rkim <-------- hostname printed == rkim 

Traceback (most recent call last):
  File "/home/forge/rkim-web-app/database/backup_mysql.py", line 28, in <module>
    file = open(path + '.env', "r")
IOError: [Errno 2] No such file or directory: '/Applications/MAMP/htdocs/code/rkim-web-app/.env'

结果:

$stmt1 = $db->prepare("SELECT title,description FROM data WHERE id='1'");
$stmt1->execute();
$data = $stmt1->fetch(PDO::FETCH_OBJ);

$stmt2 = $db->prepare("SELECT id,title FROM weeks WHERE id='2'");
$stmt2->execute();
$data->weeks[] = $stmt2->fetch(PDO::FETCH_OBJ);

$stmt3 = $db->prepare("SELECT id,name FROM user WHERE id='1'");
$stmt3->execute();
$data->user[] = $stmt3->fetch(PDO::FETCH_OBJ);

$response = new stdClass();
$response->data[] = $data;

print_r($response);
echo json_encode($response);

提供

的JSON字符串
stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [title] => name of module2
                    [description] => description of module2
                    [weeks] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => 2
                                    [title] => Week 02
                                )

                        )

                    [user] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => 2
                                    [name] => john
                                )

                        )

                )

        )

)