<?php
class DatabaseController
{
public $dbh;
protected $host;
protected $port;
protected $user;
protected $pw;
protected $db;
var $charset = "utf8mb4";
function __construct($host, $port, $user, $pw, $db) {
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pw = $pw;
$this->db = $db;
$this->Connect();
}
function __destruct() {
$this->Disconnect();
}
function Connect() {
$this->dbh = mysqli_connect($this->host, $this->user, $this->pw, $this->db, $this->port);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return null;
}
if ($this->charset != '') mysqli_set_charset($this->dbh, $this->charset);
return $this->dbh;
}
function Disconnect() {
if (isset($this->dbh)) {
mysqli_close($this->dbh);
$this->dbh = null;
}
}
// run a query that returns maximum one line
function Query($qry, $resulttype = 'a') {
$fetch = false;
if (!isset($this->dbh)) $this->Connect();
$result = mysqli_query($this->dbh, $qry);
if ($result) {
if (mysqli_affected_rows($this->dbh) > 0) {
$fetch = mysqli_fetch_array($result);
}
mysqli_free_result($result);
}
return $fetch;
}
// run a query that returns 0-n lines
function Fetch($qry, $resulttype = 'n') {
$fetch = false;
if (!isset($this->dbh)) $this->Connect();
$result = mysqli_query($this->dbh, $qry);
if ($result) {
if (mysqli_affected_rows($this->dbh) > 0) {
$fetch = array();
while ($row = mysqli_fetch_array($result)) $fetch[] = $row;
}
mysqli_free_result($result);
}
return $fetch;
}
}