1

Okay, I'm using GLOBALS to set some settings within my whole site

$tmp = $GLOBALS['_ODB']->query("SELECT * FROM `options`");
$GLOBALS['options'] = NameToTop($tmp->fetchAll(PDO::FETCH_ASSOC));

I have this as my query, then I use this function to put the returned data in an array

So I can call it by using $GLOBALS['settings']['setting1']

 function NameToTop($arr)
{
    $output = array();
    foreach ($arr as $val) {
        $output[$val['name']] = $val['value'];
    }
    return $output;
}

Then here is the settings table, I don't see why this is going wrong; I really need some help.

CREATE TABLE IF NOT EXISTS `options` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `options`
--

INSERT INTO `options` (`ID`, `name`, `value`) VALUES
(1, 'setting1', 'Name'),
(2, 'email', 'webmaster@gmail.com'),
(3, 'site_title', 'Title of Site'),

I'm getting

Call to a member function fetchAll() on a non-object

Ryan
  • 25
  • 5

1 Answers1

0

You're expecting $tmp to be a PDOStatement object in order to call fetchAll() on it but it isn't, hence the error message you're seeing.

PDO::query() returns false on failure, so this is most likely what is happening.

This comment from the PDO manual talks about the return value of query():

The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.

Use the following to make it throw an exception:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

You need to read up on error handling in PDO. Most people do tend to go down the exceptions route.

That would make your example something like this:

try {
    $tmp = $GLOBALS['_ODB']->query("SELECT * FROM `options`");
    $GLOBALS['options'] = NameToTop($tmp->fetchAll(PDO::FETCH_ASSOC));
} catch (PDOException $e) {
    // handle the error in some way
    echo $e->getMessage();
}
bcmcfc
  • 25,966
  • 29
  • 109
  • 181
  • Oh this error handling in PDO, I haven't been familiar with this, something I should really start. Thank you for the help, found out I wasn't selecting the DB in the connection right, forgot the = sign after `mysql:host` – Ryan Sep 19 '14 at 13:33