diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2022-07-09 19:40:17 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2022-07-09 19:40:17 +0300 |
commit | f7bfdf58def6aadc922e1632f407d1418269a0d7 (patch) | |
tree | d7a0b2819e6a26c11d40ee0b27267ea827fbb345 /engine/database/MySQLConnection.php |
initial
Diffstat (limited to 'engine/database/MySQLConnection.php')
-rw-r--r-- | engine/database/MySQLConnection.php | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/engine/database/MySQLConnection.php b/engine/database/MySQLConnection.php new file mode 100644 index 0000000..9b473cb --- /dev/null +++ b/engine/database/MySQLConnection.php @@ -0,0 +1,79 @@ +<?php + +class MySQLConnection extends CommonDatabase { + + protected ?mysqli $link = null; + + public function __construct( + protected string $host, + protected string $user, + protected string $password, + protected string $database) {} + + public function __destruct() { + if ($this->link) + $this->link->close(); + } + + public function connect(): bool { + $this->link = new mysqli(); + return !!$this->link->real_connect($this->host, $this->user, $this->password, $this->database); + } + + public function query(string $sql, ...$args): mysqli_result|bool { + $sql = $this->prepareQuery($sql, ...$args); + $q = $this->link->query($sql); + if (!$q) + logError(__METHOD__.': '.$this->link->error."\n$sql\n".backtrace(1)); + return $q; + } + + public function fetch($q): ?array { + $row = $q->fetch_assoc(); + if (!$row) { + $q->free(); + return null; + } + return $row; + } + + public function fetchAll($q): ?array { + if (!$q) + return null; + $list = []; + while ($f = $q->fetch_assoc()) { + $list[] = $f; + } + $q->free(); + return $list; + } + + public function fetchRow($q): ?array { + return $q?->fetch_row(); + } + + public function result($q, $field = 0) { + return $q?->fetch_row()[$field]; + } + + public function insertId(): int { + return $this->link->insert_id; + } + + public function numRows($q): ?int { + return $q?->num_rows; + } + + // public function affectedRows() { + // return $this->link->affected_rows; + // } + // + // public function foundRows() { + // return $this->fetch($this->query("SELECT FOUND_ROWS() AS `count`"))['count']; + // } + + public function escape(string $s): string { + return $this->link->real_escape_string($s); + } + +} |