Reputation: 604
I'm having trouble setting up PDO in my website framework.
I open my connection in "system.php" which is included at the beginning of every page with this code here
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass,
array( PDO::ATTR_PERSISTENT => true));
}
catch(PDOException $e) {
echo $e->getMessage();
}
and on the same file (system.ph) I call this below it:
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
define('THEME', 'themes/'.$row['value'].'/');
}
Which works perfectly!
However, when I call the same query as above on "default.php"
(which is included in the file) it comes back with:
Notice: Undefined variable: DBH in /pages/default.php on line 15
Fatal error: Call to a member function query() on a non-object
in /pages/default.php on line 15
What am I doing wrong here?
default.php
<?php
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) { echo $row['value']; }
?>
Upvotes: 1
Views: 1341
Reputation: 3078
Seems like that file isn't getting included in default.php for whatever reason. Is there a boot strapper someplace that does the including for you before default.php
is loaded?
Also, make sure that you're not getting an error on the path that loads default.php
. It seems to me that $DBH
would be undefined if there were an exception. Are you using output buffering someplace that might be cleared before you can see the echoing of the exception? You may want to consider logging your exceptions to a text file instead so that output buffering doesn't prevent you from seeing the errors which are occurring.
Upvotes: 1
Reputation: 4123
If it is inside a function add
global $DBH;
in the function before calling the query() function.
Upvotes: 1