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

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。