1

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 !

3
  • 3
    Your DB class has no method name ‘connect’ exactly as the error shows you. You have a method called ‘connection’ which looks like it should return your handle so try $connection=new DB()->connection(); Commented Sep 20, 2017 at 18:22
  • Why are you trying to connect using and existing connection? Also you realize that every you call connection() you're creating a new database connection right? Do this 1k times and you'll notice the time lag and you might kill your server. Commented Sep 20, 2017 at 18:23
  • Do you have a specific reason to make your own DB class? As it doesn't seem to offer any functionalities over the mysqli class, you would make it a lot easier on yourself to just use that. Or PDO. Commented Sep 20, 2017 at 18:51

1 Answer 1

2

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();

Sign up to request clarification or add additional context in comments.

3 Comments

Then it says "Fatal error: Call to undefined method DB::prepare()"
Ok, because there is not method implemented called prepare. public function prepare($sql){ return $this->conn($sql); }
And is also to fail with close. public function close(){ $this->conn->close()}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.