简体   繁体   中英

Calling ADODB inside a function?

I'm wondering why when i put an sql ADODB query in side a function it produces the following error:

Fatal error: Call to a member function Execute() on a non-object in -path to script-

My function is something like:

$dsn = 'mysql://user:pass@localhost/db'; 
$db = ADONewConnection($dsn);

function getem($q){
$r=$db->Execute($q);
return $r->RecordCount();
}

echo getem("select * from table");

Any ideas how to fix that?

Variable Scope Issue

You need to import $db instance into your function using global keyword:

function getem($q){
  global $db;

  $r=$db->Execute($q);
  return $r->RecordCount();
}

That should do the trick.

More Info:

variable scope issue

inside the function, the local variables of $db is not defined

ugly fix is to use global like

function getem($q)
{
  global $db;
  $r=$db->Execute($q);
  return $r->RecordCount();
} 

Or you can consider wrap the adodb as static class like

class db
{
  protected static $db;

  public static function execute($query)
  {
    if (!self::$db)  // or check object instance type
    {
      self::$db = ADONewConnection('mysql://user:pass@localhost/db');
    }

    return self::$db->execute($query);
  }
}

function getem($q)
{
  $r=db::execute($q);
  return $r->RecordCount();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM