Getting Proper JSON response in PHP - 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;
}
}
?>

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

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

Related

PHP script not receiving data

I have been looking at several php codes trying to find out the problem with my code, and why it wont receive data from post
below is my php code can any one tell me whats up with it
i am trying to send audio data with the name of the audio file through this php file
the php script is supposed to receive the audio file create then audio object and then extract the name and audio part from the file but when i send the data to test it through postman i get 400 error message as i have set it up to indicate error but i do not understand why this is happening
<?php
include_once '../../configration/database.php';
include_once '../../objects/sound.php';
// JWT TOKEN VALIDATION
$data = json_decode(file_get_contents("php://input"));
$database = new Database();
$conn = $database->getConnection();
// CONTROL
$sound = new Sound($conn);
// make sure data is not empty
if (
!is_null($data->$filename)
&& !is_null($data->$extension)
&& !is_null($data->$waveform) )
{
$sound->filename = $data->filename;
$sound->extension = $data->extension;
$sound->waveform = $data->waveform;
// create the product
if ($sound->create_new())
{
http_response_code(200);
}
else
{
http_response_code(503);
echo json_encode(array(
"message" => "Unable to create sound."
));
}
}
else {
http_response_code(400);
echo json_encode(array(
"message" => "Unable to create sound. Data is incomplete."
));
}
?>
the database.php file is as follows
<?php
include_once 'GlobalConfig.php';
class Database
{
public $conn;
public function getConnection(){
$config= new GlobalConfig();
$this->conn = null;
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
public function getConnectionAndValidate($data){
$this->conn = null;
$config= new GlobalConfig();
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
if (!validateToken($data->JWT, $data->UserID, $this->conn)){
http_response_code(401);
echo "Authorization: declined";
exit();
}
return $this->conn;
}
}
THE sound.php FILE IS AS FOLLOWS
<?php
class Sound
{
private $conn;
private $table_name = "";
public $filename;
public $extension;
public $waveform;
public $path;
public function __construct($db)
{
$this->conn = $db;
}
function create_new()
{
$this->path = $this->filename .".". $this->extension;
$myfile = fopen($this->path, "w") or die("Unable to open file!");
fwrite($myfile, $this->waveform);
fclose($myfile);
// $query = " INSERT INTO `tbl_address`
// (`contact_number`,`UserID` ,`billing_street_address`, `billing_city_address`, `billing_state_address`, `billing_country_address`, `billing_zip`,
// `shipping_street_address`, `shipping_city_address`, `shipping_state_address`, `shipping_country_address`, `shipping_zip`)
// VALUES (:contact_number,'$this->user_id', :billing_street_address, :billing_city_address, :billing_state_address, :billing_country_address, :billing_zip,
// :shipping_street_address, :shipping_city_address, :shipping_state_address, :shipping_country_address, :shipping_zip);";
// $stmt = $this->conn->prepare($query);
// $this->contact_number = htmlspecialchars(strip_tags($this->contact_number));
// $this->billing_street_address = htmlspecialchars(strip_tags($this->billing_street_address));
// $this->billing_city_address = htmlspecialchars(strip_tags($this->billing_city_address));
// $this->billing_state_address = htmlspecialchars(strip_tags($this->billing_state_address));
// $this->billing_country_address = htmlspecialchars(strip_tags($this->billing_country_address));
// $this->billing_zip = htmlspecialchars(strip_tags($this->billing_zip));
// $this->shipping_street_address = htmlspecialchars(strip_tags($this->shipping_street_address));
// $this->shipping_city_address = htmlspecialchars(strip_tags($this->shipping_city_address));
// $this->shipping_state_address = htmlspecialchars(strip_tags($this->shipping_state_address));
// $this->shipping_country_address = htmlspecialchars(strip_tags($this->shipping_country_address));
// $this->shipping_zip = htmlspecialchars(strip_tags($this->shipping_zip));
// // bind values
// $stmt->bindParam(":contact_number", $this->contact_number);
// $stmt->bindParam(":billing_street_address", $this->billing_street_address);
// $stmt->bindParam(":billing_city_address", $this->billing_city_address);
// $stmt->bindParam(":billing_state_address", $this->billing_state_address);
// $stmt->bindParam(":billing_country_address", $this->billing_country_address);
// $stmt->bindParam(":billing_zip", $this->billing_zip);
// $stmt->bindParam(":shipping_street_address", $this->shipping_street_address);
// $stmt->bindParam(":shipping_city_address", $this->shipping_city_address);
// $stmt->bindParam(":shipping_state_address", $this->shipping_state_address);
// $stmt->bindParam(":shipping_country_address", $this->shipping_country_address);
// $stmt->bindParam(":shipping_zip", $this->shipping_zip);
// if ($stmt->execute()) {
// $this->address_id = $this->conn->lastInsertId();
// }
// else {
// echo json_encode(array("message" => "Unable to get address."));
// }
}
}
?>

Run time error in PHP Static Properties and Accessing Global Instance within a Class

I designed a PHP Class with a Static Properties and I get a blank page without any error log, Kindly assist me whats wrong in my PHP Code?
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost"
static private $database = "Student";
static private $user = "ram";
static private $password = "ram12345!";
static public $link;
public static function Trigger() {
try
{
if (!isset(self::$link)) {
self::$link = mysql_connect("localhost", "bbminfoc_bbm", "Princess4BBM.>") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
if(!$response->Status)
{
unset(self::$link);
}
}
}
if(!isset(Connection::link))
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo($outp);
}
else
{
echo("No Data");
}
?>
Kindly assist me in this code, I don't know what I did wrong in the above pasted code because I can't able to see the log information in error_log file.
As #Yolo already mentioned in the comment, there's a semicolon missing in Connection::Trigger(); and at static private $server = "localhost". As this will cause a parse error the script will fail before executing and you won't see any errors.
To see those errors you will have to find the php.ini configuration file and set
display_errors = on. Also you should consider using an IDE with automatic code linting which will show you potential parse errors while typing the code.
As taken from this answer.
The completely fixed code looks like this:
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost";
static private $database = "Student";
static private $user = "ram";
static private $password = "ram12345!";
static public $link = null;
public static function Trigger() {
global $response;
try
{
if (self::$link !== null) {
self::$link = mysql_connect("localhost", "bbminfoc_bbm", "Princess4BBM.>") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
if(!$response->Status)
{
self::$link = null;
}
}
}
if(Connection::$link !== null)
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo($outp);
}
else
{
echo("No Data");
}
?>
In static private $server = "localhost" you missed the last ;
Also, i'm getting this error:
Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in ... on line 61
So, change if(!isset(Connection::link)) to if (Connection::$link !== null)
That should solve your problem.
NOTE
Please do not use mysql_* extension. It's deprecated. If you want to continue using mysql, change to PDO or mysqli
U dont need to unset connection it will automatically be unset.. after class,
u missed semicolon after localhost, u didn't call response inside function trigger...
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost";
static private $database = "listings";
static private $user = "root";
static private $password = "";
static public $link;
public static function Trigger() {
global $response;
try
{
if (!isset(self::$link)) {
self::$link = mysql_connect("localhost", "root", "") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
}
}
if(!isset(Connection::$link))
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo "hello";
echo($outp);
}
else
{
echo "hello";
echo("No Data");
}
Change this to:
if(!isset(Connection::link))
{
Connection::Trigger();
}
This:
if(!isset(Connection::$link))
{
Connection::Trigger();
}

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

mysqli connection and query

I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}

get record using if statment & pdo query in function php

i have problem with function pdo, when it will take 1 record from the database, the result is null;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
and to display
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
database is not empty, but result display
no error, and also does not display anything
If you see correctly on the following line :
$records = $obj->detailitem('product WHERE url = "$url"');
It passes the string as "$url" , not the value of $url variable.
So change it to :
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');

Categories