-1

I've been looking at this code for ages now and I cant really understand what it want from me. I keep getting the same error message no matter what I try and I've looked through other threads to no avail. The error is Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\new_serverside\sprint1.php on line 63. my code is :

<?php 
    include 'ConfigDB.php';
?>

            <?php
             if(getConnection())
                {
                    echo "Server connection successful";
                }
                else
                {
                    echo "Problem with connection";
                }


            ini_set('display_errors', 1);

            global $dbh;

            $query = $dbh->prepare("SELECT * FROM faculty"); 
            $query->execute();
            $result = $dbh->query($query);


            foreach($result as $row)
            {
                echo $row['Name'] . "<br/>"; 
            }
            ?>
user3019749
  • 81
  • 1
  • 3
  • 9

3 Answers3

0

Call var_dump() on $dbh just after the global reference.

var_dump($dbh);

You should find something in there that isn't what you're expecting.

Zahymaka
  • 6,523
  • 7
  • 31
  • 37
0

The error means that $dbh isn't an object, so you can't call the prepare() method on it. Where is $dbh initialized? Try doing var_dump($dbh); before calling prepare() to see what's really in that variable.

Rich Adams
  • 26,096
  • 4
  • 39
  • 62
0

The error sounds like $dbh hasn't initialized properly. You can make sure that won't happen in the future by using a singleton class instead of a global variable.

class DB {
    private $instance = NULL;
    private __construct() {
        // create an instance of your db handler
    }
    public static getInstance() {
        if (!$this->instance)
            $this->instance = new DB();
        return $this->instance;
    }
}

And use it in your code like this

$dbh = DB::getInstance();
kero
  • 10,647
  • 5
  • 41
  • 51
  • For anyone else who finds this, Singletons are a different kind of global is all. [Singletons are not considered a good design pattern](https://stackoverflow.com/questions/1812472/in-a-php-project-what-patterns-exist-to-store-access-and-organize-helper-objec) – Machavity Jun 02 '17 at 12:37