Skip to content

Instantly share code, notes, and snippets.

@farindra
Created January 16, 2018 07:31
Show Gist options
  • Save farindra/96697e7a4e3410aef2e2d986406b1a1a to your computer and use it in GitHub Desktop.
Save farindra/96697e7a4e3410aef2e2d986406b1a1a to your computer and use it in GitHub Desktop.
Simple MySqli Php Library Connnection database
<?php
/**
*
*/
class database
{
private $connection;
public function __construct($hostname=DB_HOST, $database=DB_NAME, $username=DB_USER, $password=DB_PASS, $port = '3306') {
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_errno) {
throw new \Exception('Error: ' . $this->connection->connect_error . '<br />Error No: ' . $this->connection->connect_errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql) {
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value) {
return $this->connection->real_escape_string($value);
}
public function countAffected() {
return $this->connection->affected_rows;
}
public function getLastId() {
return $this->connection->insert_id;
}
public function connected() {
return $this->connection->ping();
}
public function __destruct() {
$this->connection->close();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment