-4

我一直在尝试连接到 mysql 数据库,它使用以下代码:

$host = "localhost";
$username = "skander";
$password = "xxxx";
$db = "ishweb_skander";

    $conn = mysqli_connect($host, $username, $password,$db);

    if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
} 

echo "connected successfully";

然后我尝试引入一些其他组件以方便进一步编码:

class Database {

private $host = "localhost";
private $username = "skander";
public $password = "xxxxxx";
private $db = "ishweb_skander";
public $conn;

public function dbConnection()
{

    $conn = mysqli_connect($host, $username, $password,$db);

    if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
    }
    echo "connected successfully";

加载相关网站后,我收到以下信息:

警告:mysqli_connect(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO) in /home/ishweb/www/students/projects/skander/dbconfig.php on line 13 Connection failed : 拒绝用户 ''@'localhost' 的访问(使用密码:否)

为什么 ?

4

3 回答 3

0

方法中的变量未定义。

<?php 
class Database
{
    private $host;
    private $username;
    private $password;
    private $db;

    public function __construct()
    {
        $this->host = "localhost";
        $this->username = "skander";
        $this->password = "xxxxxx";
        $this->db = "ishweb_skander";
    }

    public function connect()
    {
        $conn = mysqli_connect($this->host, $this->username, $this->password, $this->db);
        if (!$conn) {
           die("Connection failed: " . mysqli_connect_error());
        }
        return $conn;
    }
}
于 2019-09-30T10:03:01.360 回答
0

我认为这里的问题是范围。您正在设置变量,然后当您尝试在函数中引用它们时,您不是在使用$this->host例如,而是使用$host. 函数内的$host变量尚未使用函数范围内的值进行初始化。

我没有测试下面的代码,但我相信在你的情况下它会是这样的:

class Database {

    private $host = "localhost";
    private $username = "skander";
    public $password = "xxxxxx";
    private $db = "ishweb_skander";
    public $conn;

    public function dbConnection()
    {

        $this->conn = mysqli_connect($this->host, $this->username, $this->password,$this->db);

        if (!$this->conn) {
            die("Connection failed: " . mysqli_connect_error());
        }
        echo "connected successfully";
    }

}
于 2019-09-30T10:04:13.860 回答
0

由于您的信息现在在课堂上。你需要用 $this 来调用你的变量。

mysqli_connect($host, $username, $password,$db);

变成

mysqli_connect($this->host, $this->username, $this->password,$this->db);
于 2019-09-30T10:04:59.643 回答