0

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

dbconnect.php

global $dbh;

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

$af_host="localhost";                                               
$af_root="root";                                                      
$af_password=""; 

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

$af_cbms_database="af_cbms";

    try  
        {  
            $dbh = new PDO("mysql:host=$af_host", $af_root, $af_password); 
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 
            $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"); 
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
         }  
    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.

indexsummary.php

global $dbh;

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


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

and soon.....

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

bdalina
  • 503
  • 10
  • 16
  • That table has value, and it's not null. – bdalina Oct 11 '16 at 10:42
  • 1
    Is that all error message ? $af_cbms_host / $af_database - is not defined (or mistypes). When your code throws an exception, you're just echo an error message and your application will run further, independent was there an error inside the database initialize code or not. Are you sure that `$dbh` has correct resource? An error says, you try to call `prepare()`-method on `null`-value, i.e. your `$dbh`-variable has `null` value. – Wizard Oct 11 '16 at 11:27
  • 1
    remove this: $af_cbms_database = "`" . str_replace("`", "``", $af_cbms_database) . "`"; it's has no logic, You've already defined db name. – num8er Oct 12 '16 at 01:35
  • @wizard, sorry about $af_cbms_host / $af_database, i just copied it in my code the $af_cbms_host is the original variable when i post it here i changed it to $af_host, but in my original file there is no problem in my variables, since it works in most of my file. so there are no mistypes. database is defined, the table in this query $stmt = $dbh->prepare("SELECT * FROM `city_tbl`"); is not empty it is correctly written. I'll post another query that calls the same PDO connection @ dbconnect.php that worked! – bdalina Oct 12 '16 at 01:38
  • @num8er, $af_cbms_database = "" . str_replace("", "``", $af_cbms_database) . "`"; I just added that line so that my que=ry would look like this query("CREATE DATABASE IF NOT EXISTS `af_cbms` "); – bdalina Oct 12 '16 at 01:42
  • (` italized quote `) sometimes it helps if my database has similar name with some tables inside thats why i put this `` – bdalina Oct 12 '16 at 01:43
  • @bdalina I know why You've placed that, but for mysql it's equally same if it's af_cbms or `af_cbms` (with tildas). also, I'm saying: You defined `$af_cbms_database="af_cbms";` and there is no logical reason to do `str_replace` it's super funny, like You don't believe Yourself that You've defined variable (: – num8er Oct 12 '16 at 01:44
  • @bdalina checkout my answer, Your problem in dbconnect.php file that does try to create database using unknown variable, and then tries to use it. – num8er Oct 12 '16 at 02:04
  • @num8er, I have also done that, but i didn't work I just mistype here in coding the variables but the original file I have doesn't have incorrect declaration of variable since it work in almost all of my files. But I agree with this line $af_cbms_database = "" . str_replace("", "``", $af_cbms_database) . ""; to change it to $dbh->query("CREATE DATABASE IF NOT EXISTS `".$af_cbms_database."`"); – bdalina Oct 12 '16 at 02:12
  • Don't forget this too: $dbh->query("USE `".$af_cbms_database."`"); cuz You create db if not exist but You're not USEing right variable too (; – num8er Oct 12 '16 at 02:15
  • @num8er, thanks! I'll do that! – bdalina Oct 12 '16 at 02:27

2 Answers2

1

1) Your problem with creating connection and creating database.

Cuz You define:

$af_cbms_database="af_cbms";

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:

<?php

global $dbh;

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

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

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:

require_once('classes/Objs.php');
Objs::set('db', $dbh, true);

and in Your another files:

$stmt = Objs::get('db')->prepare('SELECT * FROM city_tbl');
num8er
  • 18,604
  • 3
  • 43
  • 57
  • i have try this code but I have even than this $dbh = new PDO("mysql:host='localhost'", 'root', ''); $dbh->query("CREATE DATABASE IF NOT EXISTS `af_cbms`"); require_once''; was making some error, so i try include('') then all the codes were fine. but thanks to I learned something today, with another proper coding! – bdalina Oct 12 '16 at 02:26
  • what does require once throwing out? – num8er Oct 12 '16 at 02:27
  • If I'm using require_once''; it gives me an error Fatal error: Call to a member function prepare() on null in, even if i did your code suggestion, but when i change require_once to include(); your solution works, and even my old code woks. i don't know there might be something different with require_once and include, i haven't tried include_once – bdalina Oct 12 '16 at 03:23
  • Thanks for the bunos, it's cool, I'll do that! will it works if I call that inside another class or function? – bdalina Oct 12 '16 at 03:39
  • Yes, just don't forget to require_once where it's needed. – num8er Oct 12 '16 at 03:44
0

I got this problem too. The error is I call the function before the function is declared. So I changed the sequence so that I call the function after it is declared.

jpp
  • 159,742
  • 34
  • 281
  • 339