我能';我无法连接我的数据库。PHP和MySQL
我只是PHP的初学者。我无法连接我的数据库。这是我的密码:我能';我无法连接我的数据库。PHP和MySQL,php,mysql,database,wamp,Php,Mysql,Database,Wamp,我只是PHP的初学者。我无法连接我的数据库。这是我的密码: <?php require 'config.php'; class db_class { public $host =db_host; public $username =db_username; public $password =db_password; public $db_name =db_name; public $conn; public $e
<?php
require 'config.php';
class db_class {
public $host =db_host;
public $username =db_username;
public $password =db_password;
public $db_name =db_name;
public $conn;
public $error;
private function _construct ()
{
$this-> conn ();
}
private function connect () {
$this->conn=new mysqli ($this->host, $this->username, $this->password, $this->db_name);
if ($this->conn) {
$this-> error ="Fatal Error: Can't connect to lib database" .$this->conn->connect_error;
return false;
}
}
public function save ($username, $password, $first_name, $middle_name, $last_name, $student_id)
{
$reg = $this->conn->prepare ("INSERT INTO registration (username, password, first_name, middle_name, last_name, student_id) VALUES (?, ?, ?, ?, ?, ?)") or die ($this->conn->error);
$reg->bind_param ("sssss",$username,$password,$first_name,$middle_name,$last_name, $student_id);
if ( $reg->execute()) {
$reg->close();
$this->conn->close();
return true;
}
}
}
?>
正如@riggsfully所指出的,您的构造()
函数没有做任何功能。你打错了。它应该是\u construct()
方法conn()
不存在。您应该调用connect()
函数。此外,占位符的数量与变量不匹配。应该是6点
private function __construct() #you have a typo.should be __construct()
{
$this->connect(); #call connect() function
}
$reg->bind_param ("ssssss",$username,$password,$first_name,$middle_name,$last_name, $student_id);#six placeholders for six variables
看起来您正在尝试使用mysqli函数和pdo函数。
剩下的代码似乎只是PDO。尝试将连接字符串更改为pdo方法
而不是
$this->conn=new mysqli ($this->host, $this->username, $this->password, $this->db_name);
试一试
执行另一个echo$this->conn->错误
在$reg->execute()
之后,然后查看是否出现错误,然后可能值得向我们展示config.php
,这样我们就可以查看是否设置了db\u主机
等变量构造函数没有这样做!也许你应该调用$this->connect()
在那里而不是$this->conn()
您下一个问题将是保存
方法,bind_-param()
需要6个s
参数来匹配值列表中的参数数量,即$reg->bind_-param(“ssss”),…
为什么在保存数据后要关闭连接?这不是每个实例只能使用一次的情况吗?!啊,我错过了construct()之前的单个undescore(
$this->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db_name, $this->username, $this->password);