是否需要将__construct中的连接变量插入mysqli_query中?

时间:2016-05-01 13:31:18

标签: php mysqli

我开始为数据库连接创建一个PHP类,我已经创建了一个构造函数,并在该构造函数中建立了与数据库的连接。

class mysqli_db{

        function __construct()
        {
            $conn = mysqli_connect("ip","username","password");

            if (!$conn) {
                echo "Cannot connect to server";
                exit();
            }

            $db = mysqli_select_db($conn,"silvaag166_prj");

            if (!$db) {
                echo "Cannot select database";
                exit();
            }
        }

    }

我理解上面的部分,但现在我想创建一个从数据库中选择数据的功能,所以我做了这个:

public function selectAll($tablename)
        {
            return mysqli_query(?,"SELECT * FROM ".$tableName);
        }

在?我需要添加连接字符串,可以在构造函数中找到。我如何在?。

处插入连接字符串

2 个答案:

答案 0 :(得分:3)

将连接存储为类属性,然后它将可用于整个类,即其所有方法$this->conn

class mysqli_db{
    private $conn;

    function __construct()
    {
        $this->conn = mysqli_connect("ip","username","password");

        if (!$this->conn) {
            echo "Cannot connect to server";
            exit();
        }

        $db = mysqli_select_db($this->conn,"silvaag166_prj");

        if (!$db) {
            echo "Cannot select database";
            exit();
        }
    }

    public function selectAll($tablename)
    {
        return mysqli_query($this->conn,"SELECT * FROM ".$tableName);
    }

}

答案 1 :(得分:0)

您应该使用$this->conn

class mysqli_db{
    private $conn;

    function __construct()
    {
        $this->conn = mysqli_connect("ip","username","password");

        if (!$this->conn) {
            echo "Cannot connect to server";
            exit();
        }

        $db = mysqli_select_db($this->conn,"silvaag166_prj");

        if (!$db) {
            echo "Cannot select database";
            exit();
        }
    }

    public function selectAll($tablename)
    {
        return mysqli_query($this->conn,"SELECT * FROM ".$tableName);
    }

}