0

我有这个类用于连接到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

如何修复此错误?我的错误在哪里?

4

1 回答 1

2

你想要这个在你的__construct

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

当你查询时,你想要:

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

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

于 2013-03-31T11:07:36.427 回答