doomli3721
doomli3721
2016-09-14 16:28

在PHP中获取正确的JSON响应

已采纳

I am pretty new to PHP, I have referred some examples and made a code for getting data from database. but if the database is not found I am getting a text response , Can anyone suggest how to get a proper JSON response back if no database found or misconfigured

This is my $http.get method

 $http.get('client/php/popData.php')
        .success(function(data) {
            $scope.blogs = data;
        })
        .error(function(err) {
            $log.error(err);
        })

popdata.php for getting data from database

<?php
$data = json_decode(file_get_contents("php://input"));

include('config.php');

$db = new DB();

$data = $db->qryFire();

echo json_encode($data);

?>

This is my config.php

<?php
define("__HOST__", "localhost");
define("__USER__", "username");
define("__PASS__", "password");
define("__BASE__", "databasename");

class DB {
    private $con = false;
    private $data = array();

    public function __construct() {
        $this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);

        if(mysqli_connect_errno()) {
            die("DB connection failed:" . mysqli_connect_error());
        }
    }

    public function qryPop() {
        $sql = "SELECT * FROM `base` ORDER BY `id` DESC";
        $qry = $this->con->query($sql);
        if($qry->num_rows > 0) {
            while($row = $qry->fetch_object()) {
                $this->data[] = $row;
            }
        } else {
            $this->data[] = null;
        }
        $this->con->close();
    }

    public function qryFire($sql=null) {
        if($sql == null) {
            $this->qryPop();
        } else {
            $this->con->query($sql);
            $this->qryPop();    
        }
        // $this->con->close();
        return $this->data;
    }
}
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongyun3335 dongyun3335 5年前

    Use Exceptions:

    Change your class DB like this:

    public function __construct() {
        $this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
    
        if(mysqli_connect_errno()) {
            throw new Exception("DB connection failed:" . mysqli_connect_error());
        }
    }
    

    Then change your popdata.php like

    <?php
    $data = json_decode(file_get_contents("php://input"));
    
    
    include('config.php');
    
    try {
        $db = new DB();
        $data = $db->qryFire();
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
    echo json_encode($data);
    

    This way you will get error response in JSON for any Exception thrown while constructing the DB class and while executing DB::qryFire

    if you want to catch your warnings you can try modifying your DB class like the below:

    public function __construct() {
        ob_start();
        $this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
        $warning = ob_clean();
    
        if ($warning) {
            throw new Exception($warning);
        }
    
        if(mysqli_connect_errno()) {
            throw new Exception("DB connection failed:" . mysqli_connect_error());
        }
    }
    

    You can also turn off your warnings and notices by adding

    error_reporting(E_ERROR);
    

    on the top of your file

    点赞 评论 复制链接分享
  • douao7937 douao7937 5年前

    replace the line die("DB connection failed:" . mysqli_connect_error()); in DB class __construct function with

    die( json_encode( array('status' => 'error') ) );
    

    when ever the app will fail to connect to the data base it will give

    {"status": "error"}
    

    i did not checked this. but i hope it will work

    btw it's my 1st answer on stackoverflow. i'm sorry for my mistakes. correct them

    点赞 评论 复制链接分享

相关推荐