Skip to content

Instantly share code, notes, and snippets.

@glinesbdev
Last active October 4, 2017 04:56
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 glinesbdev/a16937de08f99e6fdebfb244e8aa937c to your computer and use it in GitHub Desktop.
Save glinesbdev/a16937de08f99e6fdebfb244e8aa937c to your computer and use it in GitHub Desktop.
PHP database class [IN PROGRESS]
<?php declare(strict_types = 1);
namespace CMS\Data;
include_once(__DIR__ . '/../helpers/array.php');
/**
* Database class that handles all database connections and related actions.
*
* @param $user The connecting user
* @param $pass Password for the $user
* @param $database The database to connect to
* @param $server The server the database is on
*/
class Database
{
private $connection;
private $userName;
private $password;
private $databaseName;
private $server;
private $isConnected;
private $connectionAttempts;
private $query;
public function __construct($user, $pass, $database, $server)
{
$this->userName = $user;
$this->password = $pass;
$this->databaseName = $database;
$this->server = $server;
$this->isConnected = false;
$this->connectionAttempts = 0;
$this->query = "";
}
/*
Connects to the database via MySQLi and sets the local $isConnected variable.
*/
public function connect()
{
if (!$this->isConnected)
{
$this->connection = new \mysqli($this->server, $this->userName, $this->password, $this->databaseName);
if ($this->connection->connect_errno)
{
if ($this->connectionAttempts < 2)
{
$this->reconnect();
}
else
{
echo "Sorry, something went wrong with your connection.\n";
echo "Error: Failed to make a MySQL connection to the database: <strong>$this->databaseName</strong>\n";
echo "Errno: $this->connection->connect_errno\n";
echo "Error: $this->connection->connect_error";
exit;
}
}
$this->isConnected = true;
}
}
/**
* Runs a SELECT query and returns the class object for chaining.
*
* @param $table A string of the table name
* @param $columns An array of column names or a string value ('*', 'name', etc.)
*/
public function select($table, $columns)
{
$this->query = "SELECT ";
if (\is_array($columns))
{
$index = 0;
$columnCount = \count($columns);
foreach ($columns as $c)
{
$this->query .= $c;
if (++$index != $columnCount)
{
$this->query .= ", ";
}
else
{
$this->query .= " ";
}
}
}
elseif (\is_string($columns))
{
$this->query .= $columns;
}
else
{
$this->query .= $columns . " ";
}
$this->query .= "FROM `" . \ucfirst($table) . "`";
return $this;
}
/**
* Chains a WHERE clause onto a another chainable query and returns the class object for chaining.
*
* @param $column A string of the column name
* @param $comparison A string of the comparison operator (like, =, etc.)
* @param $value A numeric or string value
*/
public function where($column, $comparison, $value)
{
$this->query .= " WHERE $column ";
if (\is_string($value))
{
if ($comparison == "like")
{
$this->query .= strtoupper($comparison) . " '%$value%'";
}
else
{
$this->query .= "$comparison '$value'";
}
}
else
{
$this->query .= $comparison . " " . $value;
}
return $this;
}
/**
* Runs an insert query and returns a boolean value.
*
* @param $table A string of the table name
* @param $columns An array of the columns names
* @param $values An array of the inserted values
*/
public function insert($table, $columns, $values)
{
$numColumns = \count($columns);
$numValues = \count($values);
$index = 0;
$query = "INSERT INTO `$table` ";
$query .= "(";
foreach ($columns as $c)
{
$query .= $c;
if (++$index !== $numColumns)
{
$query .= ", ";
}
}
$index = 0;
$query .= ") VALUES (";
foreach ($values as $v)
{
if (\is_string($v))
{
$query .= "'$v'";
}
else
{
$query .= $v;
}
if (++$index !== $numValues)
{
$query .= ", ";
}
}
$query .= ")";
return $this->connection->query($query);
}
/**
* Runs an UPDATE statement and returns the class object for chaining.
*
* @param $table A string of the table name
* @param $column A string of the column name
* @param $value A numeric or string value
*/
public function update($table, $column, $value)
{
$this->query = "UPDATE `". \ucfirst($table) . "` SET $column = ";
if (\is_string($value))
{
$this->query .= "'$value'";
}
else
{
$this->query .= $value;
}
return $this;
}
/**
* Runs a DELETE statement and returns the class object for chaining.
*
* @param $table A string of the table name
*/
public function delete($table)
{
$this->query = "DELETE FROM `" . \ucfirst($table) . "`";
return $this;
}
/*
Runs a the class' built SQL query and returns the result.
*/
public function result()
{
$result = $this->connection->query($this->query);
if (!\is_bool($result))
{
$sqlResult = $result->fetch_assoc();
$result->free();
return $sqlResult;
}
else
{
$sqlResult = $result;
$result->free();
return $result;
}
$this->connection->close();
}
/*
Returns if there is a connection to the database
*/
public function isConnected()
{
return $this->isConnected;
}
/*
Attempts to reconnect to the database if the initial 3 connections fail.
*/
private function reconnect()
{
if ($this->connectionAttempts < 2)
{
$this->connectionAttempts++;
$this->connect();
}
else
{
die("Cannot connect to database: <strong>$this->databaseName</strong>. Please check your connection information.");
}
}
}
<?php declare(strict_types = 1);
require(__DIR__ . '/../data/database.php');
$db = new CMS\Data\Database('bradyng', '', 'PHPCms', 'localhost');
$db->connect();
$table = 'user';
$column = '*';
$results = $db->select($table, $column)->where('username', 'like', 'jo')->result();
print_r($results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment