2017-07-14 63 views
2

我正在使用这个类使用mysql,但意识到它已被弃用。我试图让它使用PDO或mysqli工作,但我不是100%确定如何让它工作。使用类sqli或PDO连接到数据库

class DB { 
    private $link; 
    private $host, $username, $password, $database; 
    public function __construct($host, $username, $password, $database){ 
     $this->host  = $host; 
     $this->username = $username; 
     $this->password = $password; 
     $this->database = $database; 

     $this->link = mysqli_connect($this->host, $this->username, $this->password) 
      OR die("There was a problem connecting to the database."); 

     mysqli_select_db($this->link,$this->database) 
      OR die("There was a problem selecting the database."); 

     return true; 
    } 
    public function query($query) { 
     $result = mysqli_query($link,$query); 
     if (!$result) die('Invalid query: ' . mysqli_error()); 
     return $result; 
    } 

    public function __destruct() { 
     mysqli_close($this->link) 
      OR die("There was a problem disconnecting from the database."); 
    } 

public function gettingDepartments(){ 
     $db = new DB("localhost", "root", "", "visitorform"); 
     $result = $db->query("SELECT * FROM tb_user_dept"); 
     return $result; 
    } 


} 

这是我的错误:

警告:mysqli_query()预计参数1是mysqli的,空给出。 mysqli_error()期望的是1个参数,0给出

+0

你传递一个叫'$ link'为'mysqli_query变量()'但不设置任何地方... –

+1

我猜''结果= mysqli_query($ link,$查询);'应该可能是'$ result = mysqli_query($ this-> link,$ query);' – cteski

+1

很高兴看到有人意识到它的折旧和不完全无视这一事实。 –

回答

0

根据你的错误消息,你是不是一个有效的参数传递给mysqli_query()并没有在所有mysqli_error()

在你DBquery()方法,则需要通过一个名为$link一个局部变量,其尚未设置mysqli_query()(因此它告诉你它是null)。相反,你需要传入你的类变量。

同样,您需要将您的相同类实例变量$link传递给mysqli_error(),但您并未这样做。

你对于自己DBquery()方法更新的代码应该如下更新:

public function query($query) { 
    $result = mysqli_query($this->link, $query); 
    if (!$result) die('Invalid query: ' . mysqli_error($this->link)); 
    return $result; 
}