No result on PHP value Mysqli stmt - php

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;

Related

No JSON response from 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.

Can't connect to the database with my class?

I'm trying to connect to my database but it won't connect. I tried but won't connect. the error I'm getting is Parse error: syntax error, unexpected 'connect' (T_STRING) in C:\htdocs\www\dating\index.php on line 3. I called the tried new Database connect(); and tried connect(); I get this message Fatal error: Call to undefined function connect() in C:\htdocs\www\dating\index.php on line 3. What's wrong?
class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name = "1234";
public $conn;
// Create connection
public function connect(){
if(!isset($this->conn)){
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
if($this->conn){
$this->conn = true;
return true;
}else{
$this->conn = false;
return false;
}
}
}
public function disconnect(){
if(isset($this->conn)){
if(mysqli_close($this->conn)){
$this->myconn = false;
echo "connection closed";
return true;
} else{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
I'm trying to get use query now but it won't get the results. Here is the code
include("functions/connect.php");
$db = new Database("localhost", "12345", "1234", "123");
$db->connectdb();
$db->select('rpg');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id, username FROM users ORDER by ID DESC ";
if ($result = $db->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$db->close();`
Please change this line
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
to this
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
You will notice you used $this->pass but it should be $this->db_pass.
To call the function of Database class you have to write your code like this;
<?php
include("functions/connect.php");
$db_conn = new Database();
if($db_conn->connect()) {
echo "Database connected";
}

'cannot access empty property' error in php

I am confused where i made mistake in my php code below. Although, i looked numerous time on my code but couldn't find why i am getting this error 'cannot access empty property' .
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
Error on this line:
$this->results = self::$conn->query($query) or die("Error in database
connection".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';
In this line:
$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);
Replace self::$conn->$error with self::$conn->error.
The $ is required when accessing a static property, but not needed for instance properties.
No need of $ in $conn function
self::$conn replace with self::conn
^^^^^^

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.

Storing MySQL connection details as a function in PHP (PDO)

I'm trying out the PDO extension, and was wondering if it were possible to store the opening of the DB connection as a function that could be called whenever needed. I tried some basic stuff, but it doesn't seem to work. Can it?
Example Function
function DB() {
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$conn) {
echo "<br />MySQL SERVER CONNECTION ERROR.<br />\n";
}
if($conn) {
return $conn;
}
}
Example Useage
function is_post_id($submitted) {
try {
$id = $submitted;
DB();
//check to see if there is a post
//with an id matching the submitted query
$qPOST= $conn->prepare('SELECT COUNT(*) FROM posts WHERE id = :id');
$qPOST->execute(array('id' => $id));
//results counted
$cPOST= (int)$qPOST->fetchColumn();
if($cPOST > 0) {
return TRUE;
}
else {
return FALSE;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
call it as :
$conn = $this->DB();
OR
$conn = $className->DB();

Categories