Skip to content

How to Resolve Undefined Variable PDO Problem

Undefined Variable

Sometimes, you'd like put the block of PHP Data Object (PDO) db connection code to a separate file or function and for reusing it as needed, but you could hit the following error:

( ! ) Notice: Undefined variable: dbh in <file_path>
Call Stack
...
( ! ) Fatal error: Call to a member function prepare() on a non-object in <file-path>
Call Stack
...

This is usually because the required and real $dbh object handle is left in another scope of code, and make latter $dbh has no handle assigned at all.

Solutions

There're 3 ways can solve this:

1. Declare as a Global Variable

Add global in front of $dbh before creating a PDO object like:

...
global $dbh;
$dbh = new PDO("mysql:host=localhost;dbname=$dbname", $user, $pass, $options);

2. Save as a Global Variable

Pass the object handle to a global parameter:

...
$GLOBAL['dbh'] = new PDO("mysql:host=localhost;dbname=$dbname", $user, $pass, $options);

3. Wrap as a Reusable Function

Make a function to return the object handle to latter $dbh:

function getConn() {
  ...
  return new PDO("mysql:host=localhost;dbname=$dbname", $user, $pass, $options);
}
$dbh = getConn();
...

In my opinion, the third solution is my favorite, because it's OO-fashioned and very flexible to add another features.

Leave a Reply

Your email address will not be published.