我注意到这已被问过几次,但我找不到有效的答案。我正在编写一个类来处理我的数据库调用,并且由于某种原因无法建立连接。
这是我收到的错误:
警告:mysqli :: mysqli():( 28000/1045):拒绝访问用户&root;' @' localhost' (在...中使用密码:是)
这是尝试创建类实例的代码:
<?php
require_once 'inventoryconfig.php';
require("MySQLiClass.inc");
ini_set('display_errors',1); error_reporting(E_ALL);
echo "control";
/* works */
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
/* doesn't */
$mysqli_db = new mysqli_db($db_hostname, $db_username, $db_password, $db_database, $db_port);
?>
这是班级:
<?php
require_once 'IRCinventoryconfig.php';
require("drawTable.inc");
ini_set('display_errors',1); error_reporting(E_ALL);
class mysqli_db
{
protected $db_hostname;
protected $db_database;
protected $db_username;
protected $db_password;
protected $db_port;
protected $connection;
function __construct($db_hostname, $db_database, $db_username, $db_password, $db_port)
{
$this->db_hostname = $db_hostname;
$this->db_database = $db_database;
$this->db_username = $db_username;
$this->db_password = $db_password;
$this->db_port = $db_port;
if (!empty($db_hostname)
|| !empty($db_database)
|| !empty($db_username)
|| !empty($db_password)
|| !empty($db_port))
{
$this->_connect();
} else {
die("You did not provide enough information, please check your configuration files and try again.");
}
}
public function _connect()
{
/* echoes the correct information */
echo $this->db_hostname;
echo $this->db_database;
echo $this->db_username;
echo $this->db_password;
echo $this->db_port;
$this->connection = new mysqli($this->db_hostname, $this->db_username, $this->db_password, $this->db_database, $this->db_port)
or die("Database access failed:" . $this->connection->error);
//$this->connection = new mysqli($this->db_hostname, $this->db_username, $this->db_password, $this->db_database, $this->db_port);
//if ($this->connection->connect_error) die($this->connection->connect_error);
}
}
答案 0 :(得分:1)
您的参数以不正确的顺序提供给构造函数。
$mysqli_db = new mysqli_db($db_hostname, $db_username, $db_password, $db_database, $db_port);
function __construct($db_hostname, $db_database, $db_username, $db_password, $db_port)
构造函数应该如下所示:
function __construct($db_hostname, $db_username, $db_password, $db_database, $db_port)
答案 1 :(得分:0)
首先,所有参数都需要保存一个值:
if (!empty($db_hostname)
|| !empty($db_database)
|| !empty($db_username)
|| !empty($db_password)
|| !empty($db_port))
{
听起来不对。我建议
if (!empty($db_hostname)
&& !empty($db_database)
&& !empty($db_username)
&& !empty($db_password)
&& !empty($db_port))
{
...并且传递给构造的参数的顺序是错误的。它必须遵循mysqli构造顺序(主机,用户,通道,数据库,端口)