feat: add ORDER BY and LIMIT OFFSET methods

This commit is contained in:
Victor Westerlund 2023-10-16 12:59:43 +02:00
parent e501a61712
commit 6d4f7fc44b
2 changed files with 155 additions and 108 deletions

121
src/DatabaseDriver.php Normal file
View file

@ -0,0 +1,121 @@
<?php
namespace libmysqldriver\Driver;
use \mysqli;
use \mysqli_stmt;
use \mysqli_result;
// MySQL query builder and executer abstractions
class DatabaseDriver extends mysqli {
// Passing arguments to https://www.php.net/manual/en/mysqli.construct.php
function __construct() {
parent::__construct(...func_get_args());
}
// Create CSV from array
private static function csv(array $items): string {
return implode(",", $items);
}
/* ---- */
// Create CSV from columns
public static function columns(array|string $columns): string {
return is_array($columns)
? self::csv($columns)
: $columns;
}
// Return CSV of '?' for use with prepared statements
public static function values(array|string $values): string {
return is_array($values)
? self::csv(array_fill(0, count($values), "?"))
: "?";
}
/* ---- */
// Bind SQL statements
private function bind_params(mysqli_stmt &$stmt, mixed $params): bool {
// Convert single value parameter to array
$params = is_array($params) ? $params : [$params];
if (empty($params)) {
return true;
}
// Concatenated string with types for each parameter
$types = "";
// Convert PHP primitves to SQL primitives
foreach ($params as $param) {
switch (gettype($param)) {
case "integer":
case "double":
case "boolean":
$types .= "i";
break;
case "string":
case "array":
case "object":
$types .= "s";
break;
default:
$types .= "b";
break;
}
}
return $stmt->bind_param($types, ...$params);
}
// Execute an SQL query with a prepared statement
private function run_query(string $sql, mixed $params = null): mysqli_result|bool {
$stmt = $this->prepare($sql);
// Bind parameters if provided
if ($params !== null) {
$this->bind_params($stmt, $params);
}
// Execute statement and get retrieve changes
$query = $stmt->execute();
$res = $stmt->get_result();
// Return true if an INSERT, UPDATE or DELETE was sucessful (no rows returned)
if (!empty($query) && empty($res)) {
return true;
}
// Return mysqli_result object
return $res;
}
/* ---- */
// Execute SQL query with optional prepared statement and return array of affected rows
public function exec(string $sql, mixed $params = null): array {
$query = $this->run_query($sql, $params);
$res = [];
// Fetch rows into sequential array
while ($row = $query->fetch_assoc()) {
$res[] = $row;
}
return $res;
}
// Execute SQL query with optional prepared statement and return true if query was successful
public function exec_bool(string $sql, mixed $params = null): bool {
$query = $this->run_query($sql, $params);
return gettype($query) === "boolean"
// Type is already a bool, so return it as is
? $query
// Return true if rows were matched
: $query->num_rows > 0;
}
}

View file

@ -2,22 +2,17 @@
namespace libmysqldriver; namespace libmysqldriver;
use \mysqli; use libmysqldriver\Driver\DatabaseDriver;
use \mysqli_stmt;
use \mysqli_result;
// Streamline common MariaDB operations for LAMSdb3 require_once "DatabaseDriver.php";
class MySQL extends mysqli {
// Passing arguments to https://www.php.net/manual/en/mysqli.construct.php // Interface for MySQL_Driver with abstractions for data manipulation
class MySQL extends DatabaseDriver {
// Pass constructor arguments to driver
function __construct() { function __construct() {
parent::__construct(...func_get_args()); parent::__construct(...func_get_args());
} }
// Create CSV from array
private static function csv(array $items): string {
return implode(",", $items);
}
// Create WHERE AND clause from assoc array of "column" => "value" // Create WHERE AND clause from assoc array of "column" => "value"
private static function where(?array $filter = null): array { private static function where(?array $filter = null): array {
// Return array of an empty string and empty array if no filter is defined // Return array of an empty string and empty array if no filter is defined
@ -34,121 +29,52 @@
return [$sql, array_values($filter)]; return [$sql, array_values($filter)];
} }
/* ---- */ // Return SQL SORT BY string from assoc array of columns and direction
private static function order_by(array $order_by): string {
$sql = " ORDER BY ";
// Create CSV from columns // Create CSV from columns
public static function columns(array|string $columns): string { $sql .= implode(",", array_keys($order_by));
return is_array($columns) // Create pipe DSV from values
? self::csv($columns) $sql .= " " . implode("|", array_values($order_by));
: $columns;
return $sql;
} }
// Return CSV of '?' for use with prepared statements // Return SQL LIMIT string from integer or array of [offset => limit]
public static function values(array|string $values): string { private static function limit(int|array $limit): string {
return is_array($values) $sql = " LIMIT ";
? self::csv(array_fill(0, count($values), "?"))
: "?"; // Return LIMIT without range directly as string
if (is_int($limit)) {
return $sql . $limit;
} }
/* ---- */ // Use array key as LIMIT range start value
$offset = (int) array_keys($limit)[0];
// Use array value as LIMIT range end value
$limit = (int) array_values($limit)[0];
// Bind SQL statements // Return as SQL LIMIT CSV
private function bind_params(mysqli_stmt &$stmt, mixed $params): bool { return $sql . "{$offset},{$limit}";
// Convert single value parameter to array
$params = is_array($params) ? $params : [$params];
if (empty($params)) {
return true;
}
// Concatenated string with types for each parameter
$types = "";
// Convert PHP primitves to SQL primitives
foreach ($params as $param) {
switch (gettype($param)) {
case "integer":
case "double":
case "boolean":
$types .= "i";
break;
case "string":
case "array":
case "object":
$types .= "s";
break;
default:
$types .= "b";
break;
}
}
return $stmt->bind_param($types, ...$params);
}
// Execute an SQL query with a prepared statement
private function run_query(string $sql, mixed $params = null): mysqli_result|bool {
$stmt = $this->prepare($sql);
// Bind parameters if provided
if ($params !== null) {
$this->bind_params($stmt, $params);
}
// Execute statement and get retrieve changes
$query = $stmt->execute();
$res = $stmt->get_result();
// Return true if an INSERT, UPDATE or DELETE was sucessful (no rows returned)
if (!empty($query) && empty($res)) {
return true;
}
// Return mysqli_result object
return $res;
}
/* ---- */
// Execute SQL query with optional prepared statement and return array of affected rows
public function exec(string $sql, mixed $params = null): array {
$query = $this->run_query($sql, $params);
$res = [];
// Fetch rows into sequential array
while ($row = $query->fetch_assoc()) {
$res[] = $row;
}
return $res;
}
// Execute SQL query with optional prepared statement and return true if query was successful
private function exec_bool(string $sql, mixed $params = null): bool {
$query = $this->run_query($sql, $params);
return gettype($query) === "boolean"
// Type is already a bool, so return it as is
? $query
// Return true if rows were matched
: $query->num_rows > 0;
} }
/* ---- */ /* ---- */
// Create Prepared Statament for SELECT with optional WHERE filters // Create Prepared Statament for SELECT with optional WHERE filters
public function get(string $table, array|string $columns = null, ?array $filter = [], ?int $limit = null): array|bool { public function get(string $table, array|string $columns = null, ?array $filter = [], ?array $order_by = null, int|array|null $limit = null): array|bool {
// Create CSV string of columns // Create CSV string of columns if argument defined, else return bool
$columns_sql = $columns ? self::columns($columns) : "NULL"; $columns_sql = $columns ? self::columns($columns) : "NULL";
// Create LIMIT statement if argument is defined // Create LIMIT statement if argument is defined
$limit_sql = is_int($limit) ? "LIMIT {$limit}" : ""; $limit_sql = $limit ? self::limit($limit) : "";
// Create ORDER BY statement if argument is defined
$order_by_sql = $order_by ? self::order_by($order_by) : "";
// Get array of SQL WHERE string and filter values // Get array of SQL WHERE string and filter values
[$filter_sql, $filter_values] = self::where($filter); [$filter_sql, $filter_values] = self::where($filter);
// Interpolate components into an SQL SELECT statmenet and execute // Interpolate components into an SQL SELECT statmenet and execute
$sql = "SELECT {$columns_sql} FROM {$table} {$filter_sql} {$limit_sql}"; $sql = "SELECT {$columns_sql} FROM {$table}{$filter_sql}{$order_by_sql}{$limit_sql}";
// No columns were specified, return true if query matched rows // No columns were specified, return true if query matched rows
if (!$columns) { if (!$columns) {