111 lines
3.3 KiB
PHP
111 lines
3.3 KiB
PHP
<?php
|
|
include_once "Helpers.php";
|
|
class Connection
|
|
{
|
|
public $client = "mysql";
|
|
public $user = "root";
|
|
public $pass = "";
|
|
public $host = "127.0.0.1";
|
|
public $port = 3306;
|
|
public $database = "";
|
|
public $charset = "utf8mb4";
|
|
public $file = "";
|
|
public $connectionString = null;
|
|
public $db = null;
|
|
public $ready = false;
|
|
public function __construct(
|
|
$client,
|
|
$user,
|
|
$pass,
|
|
$host = "127.0.0.1",
|
|
$port = "3306",
|
|
$database = "",
|
|
$charset = ""
|
|
)
|
|
{
|
|
$this->client = $client;
|
|
$this->user = $user;
|
|
$this->pass = $pass;
|
|
$this->host = $host;
|
|
$this->port = $port;
|
|
$this->database = $database;
|
|
$this->charset = $charset;
|
|
}
|
|
public function connect()
|
|
{
|
|
if($this->db == null)
|
|
{
|
|
$this->db = new PDO(
|
|
$this->createConnectionString(),
|
|
$this->user,
|
|
$this->pass,
|
|
array(
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
)
|
|
);
|
|
$this->ready = true;
|
|
}
|
|
}
|
|
public function assertConnection()
|
|
{
|
|
if($this->db == null)
|
|
{
|
|
$this->connect();
|
|
if($this->ready == false)
|
|
{
|
|
throw new Exception("Connection not established");
|
|
}
|
|
};
|
|
}
|
|
public function createConnectionString()
|
|
{
|
|
if($this->connectionString)
|
|
{
|
|
return $this->connectionString;
|
|
}else{
|
|
$str = new tstring($this->client);
|
|
return $str
|
|
->concat(":", "host=", $this->host, ";")
|
|
->concat("port=", $this->port, ";")
|
|
->concat("database=", $this->database, ";")
|
|
->concat("host=", $this->host, ";");
|
|
}
|
|
}
|
|
public function exec($sql)
|
|
{
|
|
$this->assertConnection();
|
|
$effected = $this->db->exec($sql);
|
|
if($effected === false)
|
|
{
|
|
throw new Exception($this->db->errorInfo());
|
|
}else{
|
|
return $effected;
|
|
}
|
|
}
|
|
public function lastinsertid()
|
|
{
|
|
$this->assertConnection();
|
|
return $this->db->lastinsertid();
|
|
}
|
|
public function prepare($sql, $params = [])
|
|
{
|
|
$this->assertConnection();
|
|
$prepare = $this->db->prepare($sql);
|
|
if($prepare->execute($params))
|
|
{
|
|
return $prepare;
|
|
}else{
|
|
throw new Exception($this->db->errorInfo());
|
|
}
|
|
}
|
|
public function fetch($sql, $params = [])
|
|
{
|
|
$this->assertConnection();
|
|
return $this->prepare($sql, $params)->fetch(PDO::FETCH_ASSOC);
|
|
}
|
|
public function fetchAll($sql, $params = [])
|
|
{
|
|
$this->assertConnection();
|
|
return $this->prepare($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
}; |