简体   繁体   中英

Getting Proper JSON response in PHP

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM