使用PEAR连接到数据库时出错

时间:2012-03-17 21:22:44

标签: php database pear

我想使用PEAR开发一个网站,我已经建立了一个连接和断开数据库的类,但它似乎不起作用。我问你下面的代码我哪里错了?

class DB {

    private $mdb2;
    private $connected ;
    private $error;

    public function __construct(){
        $this->mdb2 = $mdb2;
        $this->connected = false;
        $this->error = "";
    }


    public function Connect(){

        require_once('config.php');

        $this->mdb2 = MDB2::connect("mysql://".$db_user.":".$db_pass."@".$db_host."/".$db_name."");
        $this->connected = true;
        if (PEAR::isError($this->mdb2))
        {
            //error handling
            $this->connected = false;
            die("Error connecting to the database!".$this->mdb2->getMessage());
        }
        return $this->connected;
    }

    public function getError(){
        return $this->error;
    }

    public function doquery($query)
    {
        if ($query != "" && $this->connected == true)
        {
            $result = $this->mdb2->query($query);
            if ($result->numRows() > 0 )
            {
                return $result;
            }
            else 
            {
                $this->error = "The Query returned 0 rows";
            }
        }
        else 
        {
            $this->error = "Invalid Query or DB Connection Closed";
        }

    }

    public function Disconnect(){
        if ($this->connected == true)
        {
            $this->connected = false;
            $this->mdb2->disconnect();
        }
        else 
        {
            $this->connected = false;
        }
    }
 }

运行此代码进行测试:

 $cdb = new DB();
 $cdb->Connect();
 $data = $cdb->doquery("SELECT test FROM test");
 $aa = 0;
if ($cdb->getError() == ""){
while ( $line = $data->fetchRow())
   $aa = $line[0];
   echo $aa;
}
 else echo $cdb->getError();
 $cdb->Disconnect();
 if ($aa == 3){
 $cdb->Connect();
 $dataa = $cdb->doquery("SELECT test FROM test");

 while ( $linea = $dataa->fetchRow())
   echo $linea[0];

 $cdb->Disconnect();
 }

抛出这个错误:

  

MDB2错误:连接失败连接:[错误消息:访问被拒绝用户'test'@'localhost'(使用密码:否)] [本机代码:1045] [本机消息:访问被拒绝用户'测试'@ 'localhost'(使用密码:NO)] ** mysql(mysql)://:xxx @ /

1 个答案:

答案 0 :(得分:0)

您确定数据库凭据是否正确? 实际上并没有说连接失败了,只是说你没有访问权限。