簡體   English   中英

在PHP中獲得正確的JSON響應

[英]Getting Proper JSON response in PHP

我對PHP還是很陌生,我已經引用了一些示例,並編寫了用於從數據庫獲取數據的代碼。 但是如果找不到數據庫,我將收到文本響應,如果沒有找到數據庫或配置錯誤,有人可以建議如何獲取正確的JSON響應

這是我的$ http.get方法

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

popdata.php用於從數據庫獲取數據

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

include('config.php');

$db = new DB();

$data = $db->qryFire();

echo json_encode($data);

?>

這是我的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;
    }
}
?>

替換行die("DB connection failed:" . mysqli_connect_error()); 在DB類__construct函數中

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

當應用程序無法連接到數據庫時,它將提供

{"status": "error"}

我沒有檢查這個。 但我希望它能起作用

順便說一句,這是我對stackoverflow的第一答案。 我為我的錯誤感到抱歉。 糾正他們

使用例外

像這樣更改您的類DB

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

    if(mysqli_connect_errno()) {
        throw new Exception("DB connection failed:" . mysqli_connect_error());
    }
}

然后像這樣更改您的popdata.php

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

這樣,您將在構造DB類和執行DB::qryFire時獲得JSON引發的任何異常的錯誤響應。

如果要捕獲警告,可以嘗試如下修改DB類:

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

您還可以通過添加以下命令來關閉警告和通知

error_reporting(E_ERROR);

在文件頂部

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM