【问题标题】:I can't connect with my database. PHP and MySQL我无法连接到我的数据库。 PHP 和 MySQL
【发布时间】: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-&gt;execute() 之后再做一个echo $this-&gt;conn-&gt;error; 看看是否有错误
  • 可能也值得向我们展示config.php,以便我们可以查看是否设置了db_host 等变量
  • 构造函数没有任何作用!也许你应该在那里打电话给$this-&gt;connect();而不是$this-&gt;conn()
  • 下一个问题将是save 方法,其中bind_param() 需要6 个s 参数来匹配值列表中的参数数量,即$reg-&gt;bind_param ("ssssss",....
  • 保存数据后为什么要关闭连接?这不是每个实例只能使用一次的情况吗?!

标签: php mysql database wamp


【解决方案1】:

正如@RiggsFolly 所指出的,您的construct() 函数没有做任何功能性的事情。你有一个错字。应该是__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

【讨论】:

  • 啊,我错过了construct()之前的单个取消标记
【解决方案2】:

看起来您正在尝试使用 mysqli 函数和 pdo 函数。 你们其余的代码似乎只是 PDO。尝试将连接字符串更改为 pdo 方法。

代替

$this->conn=new mysqli ($this->host, $this->username, $this->password, $this->db_name);

试试

$this->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db_name, $this->username, $this->password);

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2013-03-24
    • 2021-10-13
    • 2017-07-29
    • 2018-09-17
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多