全局Mysqli连接的问题

时间:2017-06-02 15:34:29

标签: php mysqli

我遇到了mysqli连接的问题。我有三个类文件和一个配置文件。主类文件是我初始化mysqli连接的地方,其他两个类文件扩展主类但连接没有被继承,我在进行查询时收到错误。

的config.php

<?php
include '-classes/Application.php';
include '-classes/class1.php';
include '-classes/class2.php';
define('DBHOST', '<HOST>');
define('DBUSER', '<USER>');
define('DBPASS', '<PASS>');
define('DBNAME', '<NAME>');
$app = new Application();
$c1 = new Class1();
$c2 = new Class2();
$c1->usernameExists('username');

Application.php

class Application {

    function __construct(){
        # Establish Connection to database
        $conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
        # Check Database Connection
        if(mysqli_connect_errno()) {

            die("Failed to connect with MySQL: ".mysqli_connect_error());
        } 
        else {
            $this->connect = $conn;
        }
    }
}

Class1和Class2 .php

class Class1 extends Application{
    public function usernameExists($username) {
        $query = "SELECT `username` FROM `account` WHERE `username`='$username'";
        $result = mysqli_query($this->connect, $query ) or die(mysqli_error($this->connect));
        if(mysqli_num_rows($result) == 1) return true;
        return false;
}

有时我会收到此错误: 警告:mysqli_query()期望参数1为mysqli,在第1行的class1.php中给出null;

有时候我根本就没有回复......

1 个答案:

答案 0 :(得分:0)

如果要保留要在整个类上使用的连接,那么首先定义变量。

class Application {
    [private | public] $connect;

    function __construct(){
        # Establish Connection to database
        $this->connect = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME) or die("Failed to connect with MySQL: ".mysqli_connect_error());
    }
}

此外,如果您使用die来管理异常,则无需将变量重新分配给另一个变量。

变量$ connect被定义为私有,如果你只想在类中加入,或者公共,如果你想在它们之外使用它们。