Link to home
Start Free TrialLog in
Avatar of imask
imask

asked on

PDO Fatal error: Call to a member function prepare() on a non-object in

I am getting Fatal error: Call to a member function prepare() on a non-object in dbh.

define("VERSION", "1.0");
define("MYSQLUSER", "");
define("MYSQLPASS", "");
define("MYSQLDB", "db");

defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null : define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']);
defined('LIB_PATH') ? null : define('LIB_PATH', $_SERVER['SCRIPT_FILENAME']);
global $dbh;

function _init( )
  {
   

   // connect to the database (persistent)
   try {
        $CRUD['dbh'] = new PDO('mysql:host=localhost;dbname=' . MYSQLDB, MYSQLUSER, MYSQLPASS, array( PDO::ATTR_PERSISTENT => true ));
		 

    } catch (PDOException $e) {
        error($e->getMessage());
    }
}

function error( $s )
{
    error_message($s);
}

function error_message( $s = "" )
{
//    global $CRUD;
    if($s) $CRUD["_ERR_ARRAY"][] = "<p class=\"error_message\">$s</p>\n";
    return isset($CRUD["_ERR_ARRAY"]) ? $CRUD["_ERR_ARRAY"] : array();
}

function get_sitemap_sql()
{

    
	$dbh = $CRUD['dbh'];
    $query = " SELECT html, TitleTag FROM content WHERE html <> 'sitemap'";
    $sth = $dbh->prepare($query);
    if($sth) $sth->execute();
    else error('get_sitemap_sql: select prepare returned no statement handle');

    $err = $sth->errorInfo();
    if($err[0] != 0) error( $err[2] );

    return($sth);
}

// START CODE ==============================================

_init();

  
  $sth = get_sitemap_sql();  
  

Open in new window

Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

$dbh as declared as global, but $CRUD['dbh'] is not. I would simply use directly $dbh

global $dbh;

function _init( )
  {
   

   // connect to the database (persistent)
   try {
        $dbh = new PDO('mysql:host=localhost;dbname=' . MYSQLDB, MYSQLUSER, MYSQLPASS, array( PDO::ATTR_PERSISTENT => true ));
             

    } catch (PDOException $e) {
        error($e->getMessage());
    }
}
...

function get_sitemap_sql()
{
 
    $query = " SELECT html, TitleTag FROM content WHERE html <> 'sitemap'";
    $sth = $dbh->prepare($query);
    if($sth) $sth->execute();
    else error('get_sitemap_sql: select prepare returned no statement handle');

    $err = $sth->errorInfo();
    if($err[0] != 0) error( $err[2] );

    return($sth);
}

// START CODE ==============================================

_init();

 
  $sth = get_sitemap_sql();
Avatar of imask
imask

ASKER

I tried both ways but I still get the same error
ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial