Search code examples
phpmysqlpdoglobal-variablesfetchall

$GLOBAL Setting a table in array Call to member function


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', '[email protected]'),
(3, 'site_title', 'Title of Site'),

I'm getting

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


Solution

  • 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();
    }