bdalina bdalina - 14 days ago 5x
PHP Question

How to fix Fatal error: Call to a member function prepare() on null in

Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\af\functions\indexdatasummary.php on line 6


global $dbh;

//Server Variables========-------------->


//Database Variables========------------>


$dbh = new PDO("mysql:host=$af_host", $af_root, $af_password);
$af_cbms_database = "`" . str_replace("`", "``", $af_cbms_database) . "`";
$dbh->query("CREATE DATABASE IF NOT EXISTS $af_database");
$dbh->query("SET CHARACTER SET utf8");
$dbh->query("USE $af_database");
catch(PDOException $e)
echo $e->getMessage();

the above code I use is working for almost all of my pages but in this page it's having an error. the way I call this is just the same way for the other file and this is the only page that returns with error.


global $dbh;

require_once '../functions/dbconnect.php';

$stmt = $dbh->prepare("SELECT * FROM `city_tbl`");

and soon.....

what do you think is causing this error? any help!


1) Your problem with creating connection and creating database.

Cuz You define:


and then You call:

$dbh->query("CREATE DATABASE IF NOT EXISTS $af_database"); 

so where in Your code You've defined $af_database variable?

2) it's too unprofessional to make this (seems like You're new to programming):

$af_cbms_database = "`" . str_replace("`", "``", $af_cbms_database) . "`";

You've already defined Your variable and then replacing it, funny, like You don't trust Yourself that You've defined variable? (:

or You cannot do it like this? :

$dbh->query("CREATE DATABASE IF NOT EXISTS `".$af_cbms_database."`"); 
$dbh->query("USE `".$af_cbms_database."`"); 

3) Don't complicate Your code wit too much of variables like $af_, be simple as in this fixed code of dbconnect.php:


global $dbh;

$host     = "localhost";                                               
$user     = "root";                                                      
$password = ""; 
$db_name  = "af_cbms";

try {  
  $dbh = new PDO("mysql:host=$host", $user, $password); 
  $dbh->query("CREATE DATABASE IF NOT EXISTS ".$db_name); 
  $dbh->query("SET CHARACTER SET utf8"); 
  $dbh->query("USE ".$db_name); 
catch(PDOException $e) {  

4) BONUS: Don't use global $dbh, because may happen that some process, some code can replace $dbh variable. Also using global vars is not in fashion (:

so have some Object that will keep shared stuff :

class Objs {
  private $data = [];

  final public static function set($key, $instance, $preventReset = false) {
    if($preventReset === true AND isset(self::$data[$key])) {
      return self::$data[$key];
    return self::$data[$key] = $instance;

  final public static function get($key, $instance) {
    return self::$data[$key];

and in Your db connection file:

Objs::set('db', $dbh, true);

and in Your another files:

$stmt = Objs::get('db')->prepare('SELECT * FROM city_tbl');