创建数据库连接作为类,并在PHP和Mysqli中的prepare语句中使用

时间:2017-09-20 18:17:52

标签: php mysqli prepared-statement

我尝试将数据库连接创建为一个类。

DB.class.php

class DB {

protected $servername = 'localhost';
protected $username = 'root';
protected $password = '';
protected $dbname = 'my_db';
protected $conn ;

public function connection(){

    $connection = new mysqli($this->servername,$this->username,$this->password,$this->dbname);

    if (mysqli_connect_errno()){
        echo 'db error'.mysqli_connect_error();
        exit();
    }
    $this->conn = $connection;
    return $this->conn;
 }
}

这堂课似乎没有任何问题。我想在另一个query.php

文件中使用这个类
include 'DB.class.php';

$connection = new DB();
$connection->connect($connection);

$stmt = $connection->prepare("INSERT INTO MyGuests (name, gender, email, 
town) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $gender, $email, $town);

$name = 'ex_name';
$gender = 'female';
$email = 'example@gmail.com';
$town = 'colombo';

$stmt->execute();
$stmt->close();
$connection->close();

但它一直显示此错误消息:

Fatal error: Call to undefined method DB::connect()

我应该在类中创建此查询以避免此错误消息吗?如果是,我该怎么办呢。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

如果你看到你的代码,那么方法连接不存在,是连接,它有任何参数。也是错误的,因为你将相同的偏移传递给它自己。

$connection = new DB();

$connection->connect($connection);必须为$connection->connection();