【发布时间】:2017-11-27 18:29:26
【问题描述】:
我只是 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 $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;
}
}
}
?>
所以当我单击提交按钮时,什么也没有发生。请帮忙。谢谢!
【问题讨论】:
-
在
$reg->execute()之后再做一个echo $this->conn->error;看看是否有错误 -
可能也值得向我们展示
config.php,以便我们可以查看是否设置了db_host等变量 -
构造函数没有任何作用!也许你应该在那里打电话给
$this->connect();而不是$this->conn() -
下一个问题将是
save方法,其中bind_param()需要6 个s参数来匹配值列表中的参数数量,即$reg->bind_param ("ssssss",.... -
保存数据后为什么要关闭连接?这不是每个实例只能使用一次的情况吗?!