php PDO 语句到 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2770273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDOStatement to json
提问by manumoomoo
How would I convert a PDOStatementto json? Is there library out there to do this?
我如何将 a 转换PDOStatement为 json?有图书馆可以做到这一点吗?
EDIT: I need to jsonify a PDO::FETCH_OBJ. Sorry, thanks for all of the responses.
编辑:我需要 jsonify 一个PDO::FETCH_OBJ. 抱歉,谢谢大家的回复。
json_encodedoes not have the ability to jsonify a PDO::FETCH_OBJ.
json_encode没有能力将PDO::FETCH_OBJ.
Thanks.
谢谢。
回答by Rwky
You can use the inbuilt php function json_encode() http://php.net/manual/en/function.json-encode.php
您可以使用内置的 php 函数 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);
回答by Amber
Use the fetchAll()method of the PDOStatement to retrieve an array of the values, and then pass that to json_encode().
使用fetchAll()PDOStatement的方法来检索值的数组,然后将其传递给json_encode().
$resultJSON = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
回答by Galen
$array = $statement->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $array );
回答by Rjw
I have also found it very useful to insert and set the PHP header('Content-Type: application/json') prior to sending back the JSON object returned by json_encode()
我还发现在发回 json_encode() 返回的 JSON 对象之前插入和设置 PHP 标头('Content-Type: application/json')非常有用
回答by Ruturajsinh Zala
Try this may be it's help you
试试这可能对你有帮助
$data = array();
if($stmt->execute()){
while ($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$data['data'] = $row;
}
}
}
if(!empty($data)){
header("Access-Control-Allow-Origin: *");//this allows coors
header('Content-Type: application/json');
print json_encode($data);
}else{
echo 'error';
}
回答by Mücahid Baris
My using code
我的使用代码
<?php
header('Content-Type: application/json');
try {
$db = new PDO("mysql: host=localhost; dbname=veritabani; charset=utf8","root","mysql");
} catch(PDOException $message) {
echo $message->getMessage();
}
$query = $db->prepare("SELECT id,product_name,product_price,delivery_date FROM teklif ORDER BY id");
$query->execute();
$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);
回答by Adonai Diófanes
Instead of using the header('Content-Type... in my php file, I used dataType: 'JSON' in my javascript file.
我没有使用 header('Content-Type... 在我的 php 文件中,而是在我的 javascript 文件中使用了 dataType: 'JSON' 。

