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 !
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.DBclass? As it doesn't seem to offer any functionalities over themysqliclass, you would make it a lot easier on yourself to just use that. Or PDO.