No JSON response from PHP - php

I have a JSON POST request being sent to index.php as part of a login application for a mobile device. I'm using an old script so I believe the problem is deprecated syntax with the PHP, as my response JSON is coming back empty. The $user below isn't doing anything as I'm just debugging.
index.php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
//$response = array('tag' => $tag, 'error' => FALSE);
// check for tag type
if ($tag == 'login') {
$id = $_POST['id'];
$password = $_POST['password'];
$user_type = $POST['user'];
// test data
$response = array('tag' => $tag, 'error' => FALSE, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
// check for user
$user = $db->getUserByIdAndPassword($user_type, $id, $password);
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
The query is run in this class, which is where I suspect I'm going wrong.
DB_Functions.php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
// destructor
function __destruct() {
}
/**
* Get user by id and password
*/
public function getUserByIdAndPassword($user_type, $id, $password) {
$t = 'T';
if ($user_type !== $t) {
$result = mysqli_query("SELECT * FROM smiths WHERE id = '$id'") or die(mysqli_error());
} else {
$result = mysqli_query("SELECT * FROM traders WHERE id = '$id'") or die(mysqli_error());
}
// check for result
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_fetch_array($result);
$retrieved_password = $result['password'];
// check for password equality
if ($retrieved_password == $password) {
return $result;
}
} else {
// user not found
return false;
}
}
}
And finally this class manages the msql connection, I think I need the $con from here for the previous mysqli_query? I'm not sure how to call it.
DB_Connect.php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// connecting to mysql
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysqli_close();
}
}
Could anyone help set me in the right direction? The JSON response is coming back with the error;
W/System.err: org.json.JSONException: End of input at character 0
[EDIT]
Alright so I have taken the following lines from DB_Connect.php and put them into the method in DB_Functions.php.
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
This then allows me to fix the syntax of msqli_query as so;
$result = mysqli_query($con, "SELECT * FROM smiths WHERE id = '$id'") or die(mysqli_error());
This has fixed my issue, however hacky/messy it may seem.

I have taken the following lines from DB_Connect.php and put them into the method 'getUserByIdAndPassword' in DB_Functions.php.
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
This then allows me to fix the syntax of msqli_query as so;
$result = mysqli_query($con, "SELECT * FROM smiths WHERE id = '$id'") or die(mysqli_error())
And this kids is why you don't use deprecated code like some Frankenstein madman.

Related

Warning: include(): Failed opening 'parth' for inclusion (include_path='.:/opt/php70/lib/php') in /bluehost parth/index.php on line 3

I upload my site and database in to cPanel bluehost When me connection database by code below it show error:
Warning: include(): Failed opening 'parth' for inclusion (include_path='.:/opt/php70/lib/php') in /bluehost parth/index.php on
line 3
so all developer help fix me for this error...
DB config
<?php
/*
* All database connection variables
*/
$host="localhost";
$username="root";
$password="";
$dbname="db_name";
$connection=mysql_pconnect($host,$username,$password) or die("connection to the server fail".mysql_error());
mysql_select_db($dbname, $connection) or die("could not open db:$dbname");
function db_connect()
{
if(!$connection)
{
return false;
}
if(!mysql_select_db($dbname, $connection))
{
return false;
}
return $connection;
}
function login($user,$pass)
{
db_connect();
$result = mysql_query("SELECT * FROM user WHERE username = '".$user."' AND password = '".$pass."'");
$num_rows = mysql_num_rows($result);
if($num_rows < 1) return false;
mysql_free_result($result);
return true;
}
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection ='utf8_general_ci'");
?>
include connection db
<?php
Include connection DB
<?php
/*
* I upload my site and database in to cPanel bluehost When me connection database by code below it show error:
*/
//error_reporting(E_ERROR|E_PARSE);
include 'atsschool/db_function.php';
if(empty($_GET['p']))
{
$_GET['p']='home';
}
if(empty($_GET['page']))
{
$_GET['page']='1';
}
if(empty($_GET['l']))
{
$_GET['l']='english';
}
?>
EDIT:
Replace the code in your connection script with code below and save it as config.php:
<?php
class DBController {
private $host = "localhost";
private $user = "DBUSERNAME"; //Replace with your own db username
private $password = "DBPASSWORD"; //Replace with your own db password
private $database = "DBNAME"; //Replace with your own db name
function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
function connectDB() {
$conn = mysql_connect($this->host,$this->user,$this->password);
return $conn;
}
function selectDB($conn) {
mysql_select_db($this->database,$conn);
}
function runQuery($query) {
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysql_query($query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}
}
?>
Then in your other scripts you're going to include the config.php like below:
<?php require_once("folder_where_config.php_is_located/config.php"); ?>
<?php
if(empty($_GET['p'])) {
$_GET['p']='home';
}
if(empty($_GET['page'])) {
$_GET['page']='1';
}
if(empty($_GET['l'])) {
$_GET['l']='english';
}
?>
What I would then recommend is trying something like this for the login, of course you can modify this to your liking later and keep in mind you don't actually wanna use the code below because mysql is deprecated:
<?php
require_once("config.php");
$db_handle = new DBController();
if(!empty($_POST['username']) && ($_POST['password'])) {
$result = mysql_query("SELECT count(*) FROM users WHERE Username=BINARY'".$_POST['username']."' AND password=BINARY'".$_POST['password']."'"); //You would use BINARY to make sure that the values match word for word, letter by letter, etc
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count<1) {
echo "error";
} else {
//place login function here
}
}
?>

No result on PHP value Mysqli stmt

there's no result on my sqli request .. like empty data.. i'm pretty sure in my database there's much data
here's my code, correct me if i got mistake on my code
<?php
// include db handler
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'include/DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
function getSliderList(){
$stmt = $this->conn->prepare("SELECT cPID, image FROM sliderImage");
$stmt->execute();
if ($stmt->num_rows > 0 ) {
$result = $stmt->get_result()->fetch_assoc();
$response[] = $result;
$stmt->close();
echo json_encode($response);
return true;
} else {
// user not found
return false;
}
}
}
$x = new DB_Functions();
$user = $x->getSliderList();
$response = Array();
if($user){
$user;
return false;
} else {
$response['error'] = "Sorry an error occured. Our Problem, not you.";
return true;
}
?>
my DB request to connect
<?php
class DB_Connect {
private $conn;
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
?>
and config.php file
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "bxxx");
define("DB_PASSWORD", "xxxx");
define("DB_DATABASE", "xxxx");
?>
i want to put the result into array.. and send this data using json_encode to use it in my app...
I don't think you need a prepared statement here, since you're not parameterizing any data. Try a simple query instead
$stmt = $this->conn->query("SELECT cPID, image FROM sliderImage");
$response = array();
while($result = $stmt->fetch_assoc()) {
$response[] = $result;
}
echo json_encode($response);
return true;

Login System with a DB Connection Class don't login. Return with else error for invalid login

I'm new with DB classes and working on it. I'm trying to make my old login system work with this DB class but it returns with my else for invalid login error, like there is no such e-mail and password in the DB. But there is.
Connection Class:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
Login Page:
<?php
include('dbConnect.php');
session_start();
$conexao = new Conexao("localhost", "root", "XXXXX", "festas");
if(isset($_POST['submit'])) {
$email = mysqli_real_escape_string($conexao,$_POST['email']);
$pass = mysqli_real_escape_string($conexao,$_POST['senha']);
$sel_user = $conexao->Query("SELECT * from contas where email='$email' AND senha='$pass'");
$check_user = mysqli_num_rows($sel_user);
$row = mysqli_fetch_assoc($sel_user);
if($check_user>0){
$_SESSION['user_email']=$email;
header('Location: ../adminpage.php');
mysqli_free_result($result);
} else {
header('Location: ../admin.php?erroLogin=1');
}
}
?>
Always it returns with the "else" header('Location: ../admin.php?erroLogin=1'). I think it could be because of "$check_user = mysqli_num_rows($sel_user);" but I tried to fix and can't. Tried also "$conexao->num_rows($sel_user).
I solved it. Here's what I did:
In DB class php:
public function Escape($sql)
{
return $this->link->real_escape_string($sql);
}
then in login php:
$email = $conexao->Escape($_POST['email']);
Thanks!

Connecting MySQL in a php file and using it in another php file

I have a config.php file such as
<?php
/**
* Database config variables
*/
define("DB_HOST", "blabla");
define("DB_USER", "blabla");
define("DB_PASSWORD", "blabla");
define("DB_DATABASE", "blabla");
?>
And I have a connect.php file such as
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
And I have a functions.php file such as
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once 'connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function insertRecord($name, $email, $gcm_regid, $password) {
// insert user into database
$response = array();
$query0 = "SELECT * FROM gcm_users WHERE name='$name'";
$result0 = mysql_query($query0);
if(mysql_fetch_array($result0) == NULL){
//insert...
// insert user into database
$query = "INSERT INTO `gcm_users`(`id`, `gcm_regid`, `name`, `email`) VALUES (NULL,'$gcm_regid','$name','$email');";
$result= mysql_query( $query);
// check for successful store
if ($result) {
// get user details
// $result2 = mysql_query("SELECT * FROM gcm_users WHERE name = '$name'") or die(mysql_error());
// return user details
// if (mysql_num_rows($result2) > 0) {
$response["success"] = 1;
$response["message"] = "record added";
// echo no users JSON
return $response;
}else{
$response["success"] = 0;
$response["message"] = "No records added";
// echo no users JSON
return $response;
}
}else{
$response["success"] = 0;
$response["message"] = "Record already exists";
// echo no users JSON
return $response;
}
}
?>
And I have a simple function that inserts a record but it doesn't work.I think the multiple file connection system has an error transfering the connection but I couldn't find why .Please help me thanks.
By the way I call this method from another file
which includes and calls this method as
include_once 'functions.php';
$db = new DB_Functions();
$res = $db->insertRecord($name, $email, $gcm_regid, $password);
echo json_encode($res);
Sorry for misleading but I use this connection through an android application and the program is always entering the else part rather than if($result) part.However when I connect without using another config.php and connect.php and just writing everything in the same file as
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once 'connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function insertRecord($name, $email, $gcm_regid, $password) {
$con = mysql_connect("blabla","blabla","blabla");
mysql_select_db('blabla');
// insert user into database
$response = array();
$query0 = "SELECT * FROM gcm_users WHERE name='$name'";
$result0= mysql_query( $query0 , $con);
if(mysql_fetch_array($result0) == NULL){
//insert...
// insert user into database
$query = "INSERT INTO `gcm_users`(`id`, `gcm_regid`, `name`, `email`) VALUES (NULL,'$gcm_regid','$name','$email');";
$result= mysql_query( $query , $con);
// check for successful store
if ($result) {
// get user details
// $result2 = mysql_query("SELECT * FROM gcm_users WHERE name = '$name'") or die(mysql_error());
// return user details
// if (mysql_num_rows($result2) > 0) {
mysql_close($con);
$response["success"] = 1;
$response["message"] = "products found";
// echo no users JSON
return $response;
}else{
mysql_close($con);
$response["success"] = 0;
$response["message"] = "No products added";
// echo no users JSON
return $response;
}
}else{
mysql_close($con);
$response["success"] = 0;
$response["message"] = "Product already exists";
// echo no users JSON
return $response;
}
}
?>
the $result is returning true and the record is added.In fact there is not error , the situation that the $result variable doesn't turn to be true when I use object oriented connection pattern.
I can't comment... anyway...
According to here, "This extension is deprecated as of PHP 5.5.0, and will be removed in the future." Consider using PDO: http://php.net/manual/en/book.pdo.php.
Also, consider checking the connection and database selection with something like this:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$con)
{
die(“Connection issue: ” . mysql_error());
}
$db_selection=mysql_select_db(DB_DATABASE);
if(!$db_selection)
{
die(“Database selection issue: ” . mysql_error());
}
*mysql_select_db will use the last connection opened with mysql_connect() if you don't pass in the connection you want to use as a second parameter. http://php.net/manual/en/function.mysql-select-db.php
After changing your DB information to suit my test environment, it worked fine so I don't think $this->db->connect(); is the issue. I'd double check that the right DB and table information is being used. Hope this helped a bit... new here.
Also your functions.php file you posted is missing a: }?>. Do you have error reporting turned on? Might want to check that the DB_Functions instance is even being made.

PHP MySQL connection error

guys!I got a littile trouble.
There is connection.inc.php in "includes" folder:
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
} // end of try block
} // end of $connectionType if
} // end of function
I use Linux for this test,and the lastest xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')
<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And when I load it in my browser:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9
So I guess $conn is not a object now,but It works when I write this code:
<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';
$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And it outputs:We have 8 pictures in DB
That's really a strange thing,I can't figure it out...Thanks guys!
Try saving the new mysqli() result as a variable, then return that variable instead. That logic makes no sense, I know, but I've had problems like that before.
$a = new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
return $a;

Categories