Skip to content

Instantly share code, notes, and snippets.

@Arinerron
Created March 21, 2018 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arinerron/8ffa05aebe070a332b56e5c29ac70358 to your computer and use it in GitHub Desktop.
Save Arinerron/8ffa05aebe070a332b56e5c29ac70358 to your computer and use it in GitHub Desktop.
<?php
/* define the database class */
class Database {
public $host = 'localhost';
public $name = '';
public $user = '';
public $pass = '';
private $mysqli;
/* constructor function, inits the database connection */
function __construct($chost, $cname, $cuser, $cpass) {
$this->host = $chost;
$this->name = $cname;
$this->user = $cuser;
$this->pass = $cpass;
$this->mysqli = new mysqli($this->getHost(), $this->getUsername(), $this->getPassword(), $this->getName());
}
/* closes the connection to the database */
function close() {
return $this->getMySQLi()->close();
}
/* returns a query object for the given parameters */
function query($query, $type='', ...$params) {
$statement = $this->getMySQLi()->prepare($query);
if(strlen($type) != 0) {
// bind parameters to query
$statement->bind_param($type, ...$params);
}
return new Query($this, $statement);
}
/* getter functions */
function getMySQLi() {
return $this->mysqli;
}
function getHost() {
return $this->host;
}
function getName() {
return $this->name;
}
function getUsername() {
return $this->user;
}
function getPassword() {
return $this->pass;
}
}
/* define the query class */
class Query {
private $mysqli;
private $statement;
private $result;
/* constructor, sets variables and stuff */
function __construct($mysqli, $statement) {
$this->mysqli = $mysqli;
$this->statement = $statement;
}
/* executes the statement */
function execute() {
$status = $this->getStatement()->execute();
$this->result = $this->getStatement()->get_result();
return $status;
}
/* closes the statement */
function close() {
return $this->getStatement()->close();
}
/* returns the number of results */
function countRows() {
return $this->getResult()->num_rows;
}
/* getter functions */
/* returns the statement object */
function getStatement() {
return $this->statement;
}
/* returns the result object */
function getResult() {
return $this->result;
}
function getRow() {
return $this->getResult()->fetch_assoc();
}
/* returns the result in an array */
function getRows() {
$rows = array();
while($row = $this->getRow()) {
$rows[] = $row;
}
return $rows;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment