PHP:致命错误:在非对象上调用成员函数query()

时间:2013-03-31 11:04:29

标签: php mysql

我有这个类连接到MySql数据库并创建/插入用户但是当我使用它时我看到错误。

我的认证课程是:

    class AuthDB {
        private $db;

        public function __construct() {
            $db = new Dbaccess();

    if (!$db->connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) ) {
     if (mysql_error() == '') 
      $database_incorrect = 'Database name is incorrect or doesn\'t exist'; 
     else 
      $database_incorrect = 'ERROR: ';
     echo $database_incorrect . mysql_error ();
    }
        }

        public function createUser($email, $password, $salt, $verification) {

            $ver = 0;
            $act = 1;
            $adm = 0;

            $MYSQLDB = "INSERT INTO tbUsers (email, password, user_salt, is_verified, is_active, is_admin, verification_code) "
            . "VALUES ('1', '1', '1', '1', '1', '1', '1')"; //test value

            $r2 = $db->query ($MYSQLDB) or error ('Critical Error', mysql_error () ); // <<<LINE 30 ERROR HERE

            if ($r2 > 0) {
                return true;
            }

            return false;
        }
   }

我的Dbaccess课程是:

class Dbaccess
{
var $q_array = array();
var $db_id;
var $query;
var $counter = 0;
var $timecounter = 0;
var $query_res;

function connect ($host, $login, $password, $db)
{
$this->host = $host;
$this->login = $login;
$this->password = $password;
$this->db = $db;
$this->db_id = @mysql_connect($this->host, $this->login, $this->password);
if ($this->db_id)
{
$db_select = @mysql_select_db($this->db);
$this->query("SET NAMES 'UTF8'");
if (!$db_select)
{
@mysql_close($this->db_id);
$this->db_id = $db_select;
}
else
return $this->db_id;
}
else
return false;
}
function close()
{
if($this->db_id)
{
if($this->query)
{
@mysql_free_result($this->query);
}
$result = @mysql_close($this->db_id);
return $result;
}
else {
return false;
}}
function query ($query)
    //
    // $db->query("QUERY");

    {

        unset($this->query_res);

        if($query != "")

        {

            $sql_start = explode(' ', microtime());

            $this->query_res = @mysql_query($query, $this->db_id);

            $sql_stop = explode(' ', microtime());
            $sql_time = $sql_stop[0] - $sql_start[0];
            $sql_time+= $sql_stop[1] - $sql_start[1];

            $this->timecounter+= round($sql_time, 5);
            $this->counter++;

        }

        if($this->query_res)

        {
            unset($this->q_array[$this->query_res]);
            return $this->query_res;
        }
        else
        {
            return false;
        }
    }
}

现在我在发送数据时看到了这个错误:

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\test\classes\Auth.php on line 30

如何解决此错误?我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

您希望在__construct

中使用此功能
public function __construct() {
  $this->db = new Dbaccess();

当您查询时,您需要:

$this->db->query($MYSQLDB);

当您使用变量$db时,它只存在于该方法的范围内。但是当你使用类属性时,它存在于整个类的范围内。