Chathuri Fernando
Chathuri Fernando

Reputation: 972

Create db connection as a class and use in prepare statement in PHP and Mysqli

I tried to create the database connection as a class.

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;
 }
}

It seems that there is no any issue with this class. I want to use this class in another file which is 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 = '[email protected]';
$town = 'colombo';

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

But it keeps showing this error message:

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

Should I create this query inside a class to avoid this error message? If yes how can I do that. Can somebody help me !

Upvotes: 1

Views: 564

Answers (1)

luis moyano
luis moyano

Reputation: 110

If you see your code, does not exists the method connect, is connection and it has any parameter. Also is wrong because you are passing the same offset to itself.

$connection = new DB();

The $connection->connect($connection); must be $connection->connection();

Upvotes: 2

Related Questions