Call to a member function query() on null in PHP - php

I am getting below error when I run my PHP code.
Call to a member function query() on null
Below is the code,
function fetch_url($url_code) {
$query = "SELECT * FROM `urls` WHERE `url_code` = ? ";
$result = $this->db->query($query, array($url_code));
if ($result) {
return $result;
} else {
return false;
}
}
Please guide me how to remove this error.

this->db->query function need only SQL Code. not like PDO.
Make sure Library is loaded
In config/autoload.php add this $autoload['libraries'] = array('database');
Try this
function fetch_url($url_code) {
$query = $this->db->query("SELECT * FROM urls WHERE url_code = '$url_code' ");
$result = $query->result_array(); # setting array to objective
$count = count($result); # get count
if (!empty($count)) {
return $result;
}
else {
return false;
}
}

Your $this->db is null. Please make sure, it is initialized properly before calling query. Here is a very basic example for MySQL (you will have to adapt it to your DB system):
function init() {
$this->db = new mysqli('host', 'user', 'password', 'database');
if (!$this->db) {
die('MySQL Connection Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
function fetch_url($url_code) {
$sql = "SELECT * FROM urls WHERE url_code = '$url_code' ";
if ($this->db === null) {
$this->init();
}
$query = $this->db->query($sql);
$result = $query->result_array(); # setting array to objective
$count = count($result); # get count
if (!empty($count)) {
return $result;
}
else {
return false;
}
}

class Database {
public $host=DB_HOST; // Specify localhost
public $username=DB_USER; //Specify username
public $password=DB_PASSWORD; // specify password
public $dbname=DB_NAME; // specify database name
public $conn ;
public $error;
/*
* Class Constructor
*/
Public function __constructor() {
// Call Connect Function
$this->connect();
}
/*
* Connector
*/
Public function connect() {
//* Creating mySqli Class Object * //
$this->conn = new mysqli($this->host,$this->username,$this->password,$this->dbname);
if (!$this->conn) {
$this->error = "Connection failed :" .$conn->connect_error ;
return false;
}
}
/*
* Select function
*/
public function select($query) {
/* to avoid call to member function query() on Null Error
Use this 2 lines of code */
if ($this->conn === null) {
$this->connect();
}
$results = $this->conn->query($query) or die($this->conn->error.__LINE__);
/* If there is atleast one row in the table Condition is true / Return table Rows as per your sql query */
if($results->num_rows > 0) {
return $results;
}
else {
return false;
}
} //Select Function Ends;
} //Class ends here ..

Yes use this lines of code to get rid of the error Call to a member function query() on null in PHP I used it in my database class and it's working fine !

class Database {
public $host='localhost'; // Your Local Computer
public $username='root'; // Your PhpMyAdmin Username
public $password=''; // Your PhpMyAdmin Password
public $dbname='blog'; // Your database Name
// Declaring Variables
public $conn ;
public $error;
/*
* Class Constructor
*/
Public function __constructor() {
// Call Connect Function
$this->connect();
}
/*
* Connector
*/
Public function connect() {
//* Creating mySqli Class Object * //
$this->conn = new mysqli($this->host,$this->username,$this->password,$this->dbname);
if (!$this->conn) {
$this->error = "Connection failed :" .$conn->connect_error ;
return false;
}
}
/*
* Select function
*/
public function select($query) {
// these 2 lines of code help to resolve error "Call to a member function query() on null " //
if ($this->conn === null) {
$this->connect();
}
$results = $this->conn->query($query) or die($mysqli->error.__LINE__);
/* If there is atleast one records in the table based on Sql Query ! Condition is true / Return table Records*/
if($results->num_rows > 0) {
return $results;
}
else {
return false;
}

Related

How to modify my PHP database extraction class to work with MySQLi

I am getting a warning stating:
mysqli_num_rows() expects parameter 1 to be mysqli_result
It has been a while since I worked with PHP which leads me to struggle figuring out why the size function in the MySQLReturn class is giving me grief. It is an old class I used years ago and modified it as best I could to work with php7 and MySQLi.
<?php
class MySQL {
private $host;
private $dbUser;
private $dbPass;
private $dbName;
private $dbConn;
private $connectError;
public function __construct($host,$dbUser,$dbPass,$dbName) {
$this->host=$host;
$this->dbUser=$dbUser;
$this->dbPass=$dbPass;
$this->dbName=$dbName;
$this->connectToDb();
}
public function __destruct() {
}
public function connectToDb () {
// Make connection to MySQL server
if (!$this->dbConn = mysqli_connect($this->host,$this->dbUser,$this->dbPass)) {
trigger_error('Could not connect to server');
$this->connectError=true;
// Select database
} else if (!mysqli_select_db($this->dbConn,$this->dbName)) {
trigger_error('Could not select database');
$this->connectError=true;
}
}
public function isError () {
if ($this->connectError)
return true;
$error=mysqli_error($this->dbConn);
if (empty($error))
return false;
else
return true;
}
public function query($sql) {
if (!$queryResource=mysqli_query($this->dbConn,$sql)) trigger_error ('Query failed: '.mysqli_error($this->dbConn).' SQL: '.$sql);
$result = new MySQLReturn($this,$queryResource);
return $result;
}
}
class MySQLReturn {
private $mysql;
private $query;
public function MySQLResult($mysql,$query) {
$this->mysql=$mysql;
$this->query=$query;
}
public function fetch() {
if ($row=mysqli_fetch_array($this->query,MYSQL_ASSOC) ) {
return $row;
} else if ( $this->size() > 0 ) {
mysqli_data_seek($this->query,0);
return false;
} else {
return false;
}
}
public function size() {
return mysqli_num_rows($this->query);
}
public function insertID() {
return mysqli_insert_id($this->mysql->dbConn);
}
public function isError() {
return $this->mysql->isError();
}
}
?>
This is how I am accessing the class functions;
<?php
$db = new MySQL($dbhost,$dbuser,$dbpass,$dbmain);
$authsql = $db->query("SELECT * FROM users WHERE email='".$uid."' AND password=MD5('".$pwd."')");
if ($authsql->size() >= '1') {
$logindtsql = $db->query("UPDATE users SET last_login=CURRENT_TIMESTAMP WHERE email='".$uid."' AND password=MD5('".$pwd."')");
$authsqlrow = $authsql->fetch();
extract($authsqlrow);
}
if ($authsql->size() == 0) {
unset($_SESSION['uid']);
unset($_SESSION['pwd']);
session_destroy();
}
?>
I am not getting the size of the query
Changed
public function MySQLResult($mysql,$query) {
$this->mysql=$mysql;
$this->query=$query;
}
to
public function __construct($mysql,$query) {
$this->mysql=$mysql;
$this->query=$query;
}
Works like a charm

I get Exception unknown error, after querying DataBase for the second time in PHP MYSQLI

I'm using this code:
class db extends mysqli
{
protected static $instance;
protected static $options = array();
private function __construct() {
$o = self::$options;
// turn of error reporting
mysqli_report(MYSQLI_REPORT_OFF);
// connect to database
#parent::__construct(isset($o['host']) ? $o['host'] : 'localhost',
isset($o['user']) ? $o['user'] : 'root',
isset($o['pass']) ? $o['pass'] : '',
isset($o['dbname']) ? $o['dbname'] : 'world',
isset($o['port']) ? $o['port'] : 3306,
isset($o['sock']) ? $o['sock'] : false );
// check if a connection established
if( mysqli_connect_errno() ) {
throw new exception(mysqli_connect_error(), mysqli_connect_errno());
}
}
public static function getInstance() {
if( !self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public static function setOptions( array $opt ) {
self::$options = array_merge(self::$options, $opt);
}
public function query($query) {
if( !$this->real_query($query) ) {
throw new exception( $this->error, $this->errno );
}
$result = new mysqli_result($this);
return $result;
}
public function prepare($query) {
$stmt = new mysqli_stmt($this, $query);
return $stmt;
}
}
I have some functions that update, insert, display DB content.
Now if I execute this code directly, no problem:
$sql = db::getInstance();
$sql->set_charset("utf8");
$sql->query("UPDATE ads SET text='moooo' WHERE id=1") ;
But if I use two functions one to display some content and the second to update, I get an unknown exception error and DB won't be updated!
Here is an example where I get error:
$sql = db::getInstance();
$sql->set_charset("utf8");
if(ad_exists($mq->id)){
$sql->query("UPDATE ads SET text='moooo' WHERE id=1") ;
}
And here is how the ad_exist function looks like:
function ad_exists($id){
$sql = db::getInstance();
$sql->set_charset("utf8");
$result = $sql1->query("SELECT * FROM ads WHERE id=".$id);
$sql->close();
if($result->num_rows>0) {$result->close();
return true;}
else {$result->close();
return false;}
}
I've been going about closing connections after queries, preparing statements instead of direct queries, trying to make db object global or passing it as a variable, nothing seems to work, can't get over this error.
I think you have a typo error in here:
$result = $sql1->query("SELECT * FROM ads WHERE id=".$id);
the 1 after $sql shouldn't be there, also try not to initiate two objects, you can pass the $sql variable into your ad_exists method and just use the $result = $sql->query("SELECT * FROM ads WHERE id=".$id); line, don't close the connection after the UPDATE is done.
Try this:
In your ad_exists method:
function ad_exists($id, &$sql) {
$result = $sql->query("SELECT * FROM ads WHERE id=".$id);
if($result->num_rows>0) {
$result->close();
return true;
} else {
$result->close();
return false;
}
}
In your code where you call your ad_exists method:
$sql = db::getInstance();
$sql->set_charset("utf8");
if(ad_exists($mq->id, $sql)) {
$sql->query("UPDATE ads SET text='moooo' WHERE id=1") ;
}
$sql->close();

How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?

How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
I have this class in php:
class DBManager
{
private $db;
private $queryResult;
public static function getInsetance()
{
static $inst = null;
if ($inst === null) {
$inst = new DBManager();
}
return $inst;
}
private function __construct()
{
$this->db = mysqli_connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()) {
echo 'DB CONNECTION ERROR';
die;
} else {
mysqli_query($this->db, 'SET NAMES UTF8');
}
}
public function _destruct()
{
mysqli_close($this->db);
}
/**
* #param $query
* #return bool|mysqli_result
*/
public function runQuery($query)
{
return $this->queryResult = mysqli_query($this->db, $query);
}
/**
* #return mysql_result
*/
public function getLastQueryResult()
{
return $this->queryResult;
}
}
And in another file, I want to do some different query. I want to get the last id of INSERT query in this code:
session_start();
require 'DBManager.php';
$db = DBManager::getInsetance();
$query = "INSERT INTO `test`(`creator`, `name`) VALUES
('$creatorid','$name')";
$result = $db->runQuery($query);
Have you tried this?
$last_id = $db->insert_id;
Source
I found:
In DBManager class i must do this changs:
public function runQuery($query)
{
$this->queryResult = mysqli_query($this->db, $query);
$last_id = mysqli_insert_id($this->db);
if($last_id !== 0){
return $last_id;
}
return $this->queryResult;
}
and i will get $result in server file.

PHP mysql_query transactions not rolling back

I have written a database class(es) sometime ago, I use this for most projects and recently extended the class to work with transactions.
The Transaction class below does not seem to work correctly, the server is MySQL innoDB and I've checked that transactions work on my database(with PHPMyAdmin). So this is obviously an error in my code or my misunderstanding.
<?php
/**
* Description of Database
*
* #author http://stackoverflow.com/users/820750/gerve
*/
class Database {
private $connection;
public function __construct($dbServer, $dbName, $dbUser, $dbPassword) {
$this->connection = mysql_connect($dbServer, $dbUser, $dbPassword);
mysql_select_db($dbName, $this->connection);
}
public function query($query, $die = true) {
return new Query($query, $this->connection, $die);
}
public function escape($param) {
return mysql_real_escape_string($param, $this->connection);
}
public function transaction() {
return new Transaction($this->connection);
}
}
class Query {
private $query;
public $count;
public $countModified;
public $queryString;
public function __construct($query, $link_identifier, $die = true) {
if($die){
$this->query = mysql_query($query, $link_identifier) or die(mysql_error());
}
else{
$this->query = mysql_query($query, $link_identifier);
}
$this->count = is_resource($this->query) ? mysql_num_rows($this->query) : 0;
$this->countModified = mysql_affected_rows($link_identifier);
$this->queryString = $query;
}
public function nextRow() {
return mysql_fetch_object($this->query);
}
public function allRows() {
$array = array();
while($row = mysql_fetch_object($this->query)){
$array[] = $row;
}
return $row;
}
}
class Transaction {
private $connection;
private $isAlive;
public function __construct($link_identifier) {
$this->connection = $link_identifier;
$this->query("BEGIN");
$this->isAlive = true;
}
public function query($query) {
if($this->isAlive){
$q = new Query($query, $this->connection, false);
if(mysql_error()){
$this->rollBack();
return false;
}
else{
return $q;
}
}
}
public function rollBack() {
if($this->isAlive){
$this->query("ROLLBACK");
$this->isAlive = false;
}
}
public function commit() {
if($this->isAlive){
$this->query("COMMIT");
$this->isAlive = false;
return true;
}
else{
return false;
}
}
}
?>
EDIT - Example usage of classes
$DB = new Database(dbServer, dbName, dbUser, dbPassword);
$transaction = $DB->transaction();
$transaction->query("INSERT INTO myTable `c1`, `c2` VALUES('1', '2')"); //Works
$transaction->query("INSERT INTO jhsdjkag 5dafa 545"); //Fails
$transaction->query("INSERT INTO myTable2 `c1`, `c2` VALUES('3', '4')"); //Works
$transaction->commit();
The above code should not insert any rows into the database, the second query has failed so none should succeed.
My problem is that it doesn't rollback, always rows are inserted regardless of failing queries.
try using START TRANSACTION instead of BEGIN
by the way START TRANSACTION will allow you to use WITH CONSISTENT SNAPSHOT:
The WITH CONSISTENT SNAPSHOT option starts a consistent read for storage engines that are capable of it. This applies only to InnoDB.
source: MySQL Documentation
I Found that there was an error in the code, just in the __construct(). It was pretty simple, I just changed 1 line:
FROM:
public function __construct($link_identifier) {
$this->connection = $link_identifier;
$this->query("BEGIN");
$this->isAlive = true;
}
TO:
public function __construct($link_identifier) {
$this->connection = $link_identifier;
$this->isAlive = true;
$this->query("BEGIN");
}
->isAlive was being set after the first "BEGIN" query, which means BEGIN was never sent.

Call to undefined function mysqli_result::num_rows()

I'm trying to count the number of rows in a result, and I keep getting the above returned error. I've checked the manual, and I'm using mysqli_result::num_rows() as I should be (I'm using object oriented style.) I've got three classes working here.
Class (Connection):
class utils_MysqlImprovedConnection {
protected $_connection;
public function __construct($host, $user, $pwd, $db)
{
$this->_connection = #new mysqli($host, $user, $pwd, $db);
if(mysqli_connect_errno ()) {
throw new RuntimeException('Cannot access database:' . mysqli_connect_error());
}
}
public function getResultSet($sql)
{
$results = new utils_MysqlImprovedResult($sql, $this->_connection);
return $results;
}
public function __destruct() {
$this->_connection;
}
}
Class (Handles Result):
class utils_MysqlImprovedResult implements Iterator, Countable {
protected $_key;
protected $_current;
protected $_valid;
protected $_result;
public function __construct($sql, $connection) {
if (!$this->_result = $connection->query($sql)){
throw new RuntimeException($connection->error . '. The actual query submitted was: '. $sql);
}
}
public function rewind()
{
if (!is_null($this->_key)){
$this->_result->data_seek(0);
}
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
}
public function valid()
{
return $this->_valid;
}
public function current()
{
return $this->_current;
}
public function key()
{
return $this->_key;
}
public function next()
{
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
$this->_key++;
}
public function count()
{
$this->_result->store_result();
$this->_result->num_rows();
}
}
Class function:
public function resetPassword($email, $pass){
//check if email exists, update authkey and password, send email
$sql = "SELECT * FROM table WHERE column = '$email'";
$results = $this->_db->getResultSet($sql);
if($results->count() == 1){
// Process
$this->_message = "Success!";
return $this->_message;
} else {
// Not unique
$this->_error = "Try again";
return $this->_error;
}
}
The test page I'm using to call all this is (include statement is just __autoload() function that is working fine):
$columnvar = 'emailaddress#test.com';
$pass = 'blah';
require_once 'inc.init.php';
$user = new utils_User();
try{
$string = $user->resetPassword($email, $pass);
echo $string;
}
catch(Exception $e) {
echo $e;
}
From the manual, it seems that mysqli_result::num_rows isn't a function, but rather a variable containing the number of rows.
It can be used like this:
$num_rows = $mysqli_result->num_rows;
The function equivalent is mysqli_num_rows($result), where you pass in the mysqli_result object, but that's if you're using the procedural style rather than object oriented style.
In your code, you should change your count() function in the utils_MysqlImprovedResult class to be like this (I'm assuming that's the function where you're getting the error message),
public function count()
{
// Any other processing you want
// ...
return $this->_result->num_rows;
}
or alternatively if you want to mix OO and procedural styles (probably a bad idea),
public function count()
{
// Any other processing you want
// ...
return mysqli_num_rows($this->_result);
}

Categories