blessing-skin-server/app/Services/Database.php

235 lines
6.0 KiB
PHP
Raw Normal View History

<?php
2016-12-17 22:56:00 +08:00
namespace App\Services;
2016-03-18 17:49:52 +08:00
use Exception;
use Illuminate\Support\Arr;
use InvalidArgumentException;
2016-07-21 22:01:57 +08:00
/**
* Light-weight database helper
*
* @author <h@prinzeugen.net>
2016-07-21 22:01:57 +08:00
*/
2016-08-24 22:43:04 +08:00
class Database
{
2016-07-21 22:01:57 +08:00
/**
* Instance of MySQLi.
2016-08-14 08:31:07 +08:00
*
2016-07-21 22:01:57 +08:00
* @var null
*/
private $connection = null;
2016-08-14 08:31:07 +08:00
/**
* Database name.
2016-08-14 08:31:07 +08:00
*
* @var array
*/
private $database = "";
2016-08-14 08:31:07 +08:00
2016-07-21 22:01:57 +08:00
/**
* Name of table to do operations in.
2016-08-14 08:31:07 +08:00
*
2016-07-21 22:01:57 +08:00
* @var string
*/
private $tableName = "";
2016-07-21 22:01:57 +08:00
/**
* Construct with a config array.
2016-07-21 22:01:57 +08:00
*
* @param array $config
*/
2016-08-14 08:31:07 +08:00
public function __construct($config = null)
2016-07-28 12:01:00 +08:00
{
try {
$this->connection = self::prepareConnection($config);
} catch (Exception $e) {
// throw with message
throw new InvalidArgumentException("Could not connect to MySQL database. ".
$e->getMessage(), $e->getCode());
}
$this->database = Arr::get($config, 'database', config('database.connections.mysql.database'));
$this->connection->query("SET names 'utf8'");
}
/**
* Try to connect to the database with given config.
*
* @param array $config
* @return \mysqli
*
* @throws InvalidArgumentException
*/
public static function prepareConnection($config = null)
{
$config = $config ?: config('database.connections.mysql');
// use error control operator to hide warnings
@$conn = new \mysqli(
$config['host'],
$config['username'],
$config['password'],
$config['database'],
$config['port']
2016-07-28 12:01:00 +08:00
);
if ($conn->connect_error) {
throw new InvalidArgumentException($conn->connect_error, $conn->connect_errno);
}
2016-07-28 12:01:00 +08:00
return $conn;
2016-08-14 08:31:07 +08:00
}
public function table($tableName, $no_prefix = false)
2016-08-14 08:31:07 +08:00
{
if ($this->connection->real_escape_string($tableName) == $tableName) {
$this->tableName = $no_prefix ? "{$this->database}.$tableName" : config('database.connections.mysql.prefix').$tableName;
2016-08-14 08:31:07 +08:00
return $this;
2016-08-14 08:31:07 +08:00
} else {
throw new InvalidArgumentException('Table name contains invalid characters', 1);
2016-08-14 08:31:07 +08:00
}
2016-03-26 19:05:09 +08:00
}
2016-03-18 17:54:19 +08:00
2016-07-28 12:01:00 +08:00
public function query($sql)
{
// compile patterns
$sql = str_replace('{table}', $this->tableName, $sql);
$result = $this->connection->query($sql);
if ($this->connection->error)
throw new Exception("Database query error: ".$this->connection->error.", Statement: ".$sql, -1);
return $result;
}
2016-07-28 12:01:00 +08:00
public function fetchArray($sql)
{
return $this->query($sql)->fetch_array();
}
/**
* Select records from table
*
* @param string $key
* @param string $value
* @param array $condition See function `where`
* @param string $table Which table to operate
* @param bool $dont_fetch_array Return resources if true
* @return array|resources
*/
2016-07-28 12:01:00 +08:00
public function select($key, $value, $condition = null, $table = null, $dont_fetch_array = false)
{
$table = $table ?: $this->tableName;
if (isset($condition['where'])) {
$sql = "SELECT * FROM $table".$this->where($condition);
} else {
$sql = "SELECT * FROM $table WHERE $key='$value'";
}
if ($dont_fetch_array) {
return $this->query($sql);
} else {
return $this->fetchArray($sql);
}
}
2016-07-28 12:01:00 +08:00
public function insert($data, $table = null)
{
$keys = "";
$values = "";
$table = $table ?: $this->tableName;
foreach($data as $key => $value) {
if ($value == end($data)) {
$keys .= '`'.$key.'`';
$values .= '"'.$value.'"';
} else {
$keys .= '`'.$key.'`,';
$values .= '"'.$value.'", ';
}
}
$sql = "INSERT INTO $table ({$keys}) VALUES ($values)";
return $this->query($sql);
2016-03-06 14:12:12 +08:00
}
2016-08-10 22:46:17 +08:00
public function has($key, $value, $table = null)
{
return ($this->getNumRows($key, $value, $table) != 0) ? true : false;
}
public function hasTable($tableName)
2016-08-10 22:46:17 +08:00
{
$sql = "SELECT table_name FROM `INFORMATION_SCHEMA`.`TABLES` WHERE (table_name = '$tableName') AND TABLE_SCHEMA='{$this->database}'";
2016-08-10 22:46:17 +08:00
return ($this->query($sql)->num_rows != 0) ? true : false;
}
2016-07-28 12:01:00 +08:00
public function update($key, $value, $condition = null, $table = null)
{
$table = $table ?: $this->tableName;
return $this->query("UPDATE $table SET `$key`='$value'".$this->where($condition));
}
2016-07-28 12:01:00 +08:00
public function delete($condition = null, $table = null)
{
$table = $table ?: $this->tableName;
return $this->query("DELETE FROM $table".$this->where($condition));
}
2016-07-28 12:01:00 +08:00
public function getNumRows($key, $value, $table = null)
{
$table = $table ?: $this->tableName;
$sql = "SELECT * FROM $table WHERE $key='$value'";
return $this->query($sql)->num_rows;
}
2016-07-28 12:01:00 +08:00
public function getRecordNum($table = null)
{
$table = $table ?: $this->tableName;
$sql = "SELECT * FROM $table WHERE 1";
return $this->query($sql)->num_rows;
}
/**
* Generate where statement
*
* @param array $condition e.g. array('where'=>'username="shit"', 'limit'=>10, 'order'=>'uid')
* @return string
*/
2016-07-28 12:01:00 +08:00
private function where($condition)
{
$statement = "";
if (isset($condition['where']) && $condition['where'] != "") {
$statement .= ' WHERE '.$condition['where'];
}
if (isset($condition['order'])) {
$statement .= ' ORDER BY `'.$condition['order'].'`';
}
if (isset($condition['limit'])) {
$statement .= ' LIMIT '.$condition['limit'];
}
return $statement;
}
2016-08-14 08:31:07 +08:00
public function __destruct()
2016-07-28 12:01:00 +08:00
{
if (!is_null($this->connection)) {
$this->connection->close();
}
}
}