<?php
class DatabaseHandler {
private $servername = CONFIG_DB_HOST;
protected $database = CONFIG_DB_NAME;
// private $username = "musiceri_bot";
private $username = CONFIG_DB_USER;
private $password= CONFIG_DB_PWD;
private $port= 3306;
// private $password= '';
public static $singleConnection = null;
public $connection = null;
public $botUsername;
public $botDatabaseId;
public $botToken;
public static $databaseName = CONFIG_DB_NAME ;
function __construct(string $botUsername){
$this->botUsername = $botUsername;
$this->init();
$this->connect();
$this->botDatabaseId = $this->getBot($botUsername);
}
function init(){
if($_SERVER['SERVER_NAME']=="towist.com"){
$this->servername = CONFIG_DB_HOST_ENGLISH;
$this->database = CONFIG_DB_NAME_ENGLISH;
$this->username = CONFIG_DB_USER_ENGLISH;
$this->password = CONFIG_DB_PWD_ENGLISH;
}
if($_SERVER['SERVER_NAME']=="unittest"){
$this->servername = "127.0.0.1";
$this->database = "test_db";
$this->username = "devuser";
$this->password = "devpass";
$this->port = 9906;
}
else if($this->botUsername =="@Test_TranslateGerman_bot") {
$this->database = CONFIG_DB_NAME_TEST;
}
}
public function connect(){
if(DatabaseHandler::$singleConnection != null){
$this->connection = DatabaseHandler::$singleConnection;
return true;
}
DatabaseHandler::$singleConnection = new mysqli($this->servername, $this->username, $this->password, $this->database, $this->port);
if (DatabaseHandler::$singleConnection->connect_error) {
throw new Exception("Connection failed: " . DatabaseHandler::$singleConnection->connect_error);
// die("Connection failed: " . DatabaseHandler::$singleConnection->connect_error);
}
$this->connection = DatabaseHandler::$singleConnection;
}
public function getBot($botUsername){
$sql = "SELECT id,token FROM `bots` WHERE `username` = '".$botUsername."'";
$result = $this->connection->query($sql);
$bot = mysqli_fetch_row($result);
if(isset($bot[0]))
return $bot[0];
else return "null";
// $this->botToken=$bot[1];
}
public function removeAllUserActivites()
{
$sql = "DELETE FROM ". $this->database . ".`user_activities`";
$result = $this->connection->query($sql) or die($this->connection->error);
return true;
}
public function getConnection(){
return $this->connection;
}
public function disconnect(){
mysqli_close($this->getConnection());
$this->connection = null;
DatabaseHandler::$singleConnection = null;
}
function query($sql){
$result = $this->connection->query($sql);
if(!empty($this->connection->error)){
throw new Exception($this->connection->error);
}
return $result;
}
}