开发者

PDOStatement to JSON [closed]

开发者 https://www.devze.com 2022-12-29 18:42 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 3 years ago.

开发者_如何学JAVA Improve this question

How would I convert a PDOStatement to JSON?

I need to jsonify a PDO::FETCH_OBJ.

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


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);


Use the fetchAll() method of the PDOStatement to retrieve an array of the values, and then pass that to json_encode().

$resultJSON = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));


$array = $statement->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $array );


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()


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 cors
        header('Content-Type: application/json');
        print json_encode($data);
    }else{
      echo 'error';
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消