Uncaught Error: Call to a member function prepare() on null in

Received above error at db_functions.php:21
Below is my code:

  1. config.php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASSWORD","");
define("DB_DATABASE","test_db");

2)db_connect.php

class DB_Connect {
	private $conn;

	public function connect(){
		
		require_once 'config.php';
		$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
		return $this->conn;
	}	
}	

3)db_functions.php

class DB_Functions{
	private $conn;

	function _construct() {
		require_once 'db_connect.php';
		$db = new DB_Connect();
		$this->conn = $db->connect();
	}

	function _destruct() {

	}

	/* 
	 * Check user exists and reture true/false
	 */
	function checkExistsUser($mobile) {
		$stmt = $this->conn->prepare("SELECT * FROM Users WHERE Mobile=?");
		$stmt->bind_parm("s", $mobile);
		$stmt->execute();
		$stmt->store_result();

		if($stmt->num_rows > 0) {
			$stmt->close();
			return true;
		} else {
			$stmt->close();
			return false;
		}
	}
}

4)register.php

require_once 'db_functions.php';
$db = new DB_Functions();
$response = array();
if(isset($_POST['mobile']) && isset($_POST['name']) && isset($_POST['birthdate']) && isset($_POST['address']) && isset($_POST['area']) && isset($_POST['city']) ){
	
	$mobile = $_POST['mobile'];
	$name = $_POST['name'];
	$birthdate = $_POST['birthdate'];
	$address = $_POST['address'];
	$area = $_POST['area'];
	$city = $_POST['city'];
	

	if($db->checkExistsUser($mobile)){
		$response["error_msg"] = "User already exists with ".$mobile;
		echo json_encode($response);
	} else {
		//Create new user
		$user = $db->registerNewUser($mobile, $name, $birthdate, $address, $area, $city);
		if($user){
			$response["mobile"] = $user["Mobile"];
			$response["name"] = $user["Name"];
			$response["birthdate"] = $user["Birthdate"];
			$response["address"] = $user["Address"];
			$response["area"] = $user["Area"];
			$response["city"] = $user["City"];
			echo json_encode($response);	
		} else {
			$response["error_msg"] = "Unknow error occured in registration!";
		echo json_encode($response);
		}
	} 

} else {
		$response["error_msg"] = "Required parameter (mobile, name, birthdate, address, area, city) is missing!";
		echo json_encode($response);
}

For testing purpose, called register.php in Advanced REST client then received above error message.
Could you please let me know how to resolve this issue.
Thanks in advance.

Even though I use PDO instead of Mysqli this is what I do and I think it might solve your problem.

Here’s my PDO connection class:

<?php

namespace Miniature;

# PDO database: only one connection is allowed. 

use PDO;

class Database {

    private $_connection;
    // Store the single instance.
    private static $_instance;

    // Get an instance of the Database.
    // @return Database: 
    public static function getInstance() {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // Constructor - Build the PDO Connection:
    public function __construct() {
        $db_options = array(
            /* important! use actual prepared statements (default: emulate prepared statements) */
            PDO::ATTR_EMULATE_PREPARES => false
            /* throw exceptions on errors (default: stay silent) */
            , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            /* fetch associative arrays (default: mixed arrays)    */
            , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        $this->_connection = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
    }

    // Empty clone magic method to prevent duplication:
    private function __clone() {
        
    }

    // Get the PDO connection:    
    public function getConnection() {
        return $this->_connection;
    }

}

then in my class that I want to access the database table I do this:

<?php

namespace Miniature;

use PDO;
use Miniature\Database as DB;

class Journal {

    public $content = null;

    static protected function pdo() {
        $db = DB::getInstance();
        $pdo = $db->getConnection();
        return $pdo;
    }

    public function editArticle($id = NULL) {
        $this->query = 'SELECT id, user_id, author, page_name, image_path, post, thumb_path, heading, content, DATE_FORMAT(date_added, "%W, %M %e, %Y") as date_added, date_added as myDate FROM journal WHERE id=:id';
        $this->stmt = static::pdo()->prepare($this->query);
        $this->stmt->bindParam(':id', $id);
        $this->stmt->execute();
        $this->row = $this->stmt->fetch(PDO::FETCH_OBJ);
        return $this->row;
    }

    
    public function insert($content) {
        $this->query = 'INSERT INTO journal( content, date_updated, date_added ) VALUES ( :content, NOW(), NOW() )';
        $this->stmt = static::pdo()->prepare($this->query);
        $this->result = $this->stmt->execute([':content' => $content]);
        return true;
        
    }

I use namespaces as I find it easiest and it’s simple to set up using composer. HTH - John

Thank you so much sir for your kind help.
However I have received that code from my colleague which is working fine for him but facing issue for me for null operation on prepare() method in db_functions.php at line 21, not sure why?
I would be grateful if you could find bug in my code meanwhile I will try your code.

It looks like the database connection

public function connect(){
	
	require_once 'config.php';
	$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
	return $this->conn;
}	

is the source of your problem. Doing it the way you are doing it the only way I can see fixing it would to do something like

require_once '_path_to_file/config.php';

in your php file not the class. The constants should then be global throughout the php code.

I have mine set up like this on my page:

Here’s a small portion to explain what I am talking about

<?php
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

use Miniature\Calendar;
use Miniature\Users as Login;
use Miniature\Trivia;

$trivia = new Trivia();

$clearDate = $trivia->clearTable();

//PHP array containing forenames.
$names = [
    'Sir',
    'King',
    'Buzz',
    'Willy'
];

shuffle($names);

or just put the constants values straight into the connection.

The reason for the error is because wherever you copied php’s OOP (Object Oriented Programming) syntax for a constructor from didn’t include actually learning the meaning and requirements for defining a constructor (programming is a written subject and you must actually learn the meaning of the syntax you are writing.) Two __ underscores are part of the name for the constructor, not one.

Next, this code is not what OOP is about. You shouldn’t be adding class/method definitions around parts of your main procedural code and calling it OOP. All that is doing is adding an unnecessary layer of syntax, that doesn’t add any value to what you are doing. You have 9-10 lines of code and unused/unneeded properties, who’s only purpose is to execute the 2 actual lines of code needed to make the database connection, which is missing useful error handling. Does that seem like using this method (programming pun intended) saved you any time writing the code? User written classes, methods, and functions should be general purpose, reusable, building blocks, that do something useful, that eliminate repetition, and make it easier to write applications. If you want to do something useful, extend the database extension you are using, with a general purpose query method, that accepts a second optional array parameter of prepared query input values to control if a prepared or a non-prepared query is used, that also adds useful error handling (using exceptions for errors), that will make it easier for you to write the database potion of your application without repeating the same lines of code over and over for each query.

Thank you so much sir for you information.
It is working now as I made some changes as per your code.

Sponsor our Newsletter | Privacy Policy | Terms of Service