doomli3721 2016-09-14 16:28
浏览 70
已采纳

在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 2016-09-14 16:49
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿