PDO 语句转 JSON

2021-12-26 00:00:00 json php pdo

如何将 PDOStatement 转换为 JSON?

How would I convert a PDOStatement to JSON?

我需要对 PDO::FETCH_OBJ 进行 jsonify.

I need to jsonify a PDO::FETCH_OBJ.

json_encode 无法对 PDO::FETCH_OBJ 进行 jsonify.

json_encode does not have the ability to jsonify a PDO::FETCH_OBJ.

推荐答案

您可以使用内置的 php 函数 json_encode() http://php.net/manual/en/function.json-encode.php

You can use the inbuilt php function json_encode() http://php.net/manual/en/function.json-encode.php

要对结果进行编码,请使用类似

To encode the results use something like

<?php
$pdo = new PDO("mysql:dbname=database;host=127.0.0.1", "user", "password");
$statement = $pdo->prepare("SELECT * FROM table");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);

相关文章