1

I keep getting "Fatal error: Call to a member function prepare() on a non-object in /var/www/html/portal_core/build_portal.php on line 30". I am new to PDO and I'm really using this as a test to get my head around it. could you guys help me to understand what I am doing wrong ?

 <?php

class build_portal 
{
protected $dbh; 

function __construct($dbname,$theme)
{
    try
    {
    $dbh = new PDO('mysql:dbname='.$dbname.';host=localhost',"username","password");
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->log_error("Construct 1st Try statement 3rd Line");
    }
    catch (PDOException $e)
    {
        echo "Page Could Not Be Loaded";
        return -1;
    }



}

function log_error($cause)
{
    try
    {
    $sth = $this->dbh->prepare("SELECT * from portal_errors");
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();
    }
    catch (PDOException $e)
    {
        print_r($e->errorInfo);
    }
}

} ?>

1 Answer 1

2

It looks to be a matter of scope. You ought to assign dbh to $this->dbh in the constructor. When you access it later in log_error(), you are expecting it to be a class property but it was originally defined as a local variable in the constructor.

$this->dbh = new PDO('mysql:dbname='.$dbname.';host=localhost',"username","password");
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh God damn it, soon as I started reading it I knew what I'd done thanks mate. Its always the small little stuff that catches you out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.