mirror of
https://codeberg.org/vlw/php-mysql.git
synced 2025-09-14 16:43:42 +02:00
Compare commits
No commits in common. "master" and "1.1.1" have entirely different histories.
7 changed files with 124 additions and 704 deletions
48
.gitignore
vendored
48
.gitignore
vendored
|
@ -1,48 +0,0 @@
|
||||||
# Bootstrapping #
|
|
||||||
#################
|
|
||||||
/node_modules
|
|
||||||
/public/hot
|
|
||||||
/public/storage
|
|
||||||
/storage/*.key
|
|
||||||
/vendor
|
|
||||||
.env
|
|
||||||
.env.backup
|
|
||||||
.phpunit.result.cache
|
|
||||||
Homestead.json
|
|
||||||
Homestead.yaml
|
|
||||||
npm-debug.log
|
|
||||||
yarn-error.log
|
|
||||||
|
|
||||||
# OS generated files #
|
|
||||||
######################
|
|
||||||
.DS_Store
|
|
||||||
.DS_Store?
|
|
||||||
._*
|
|
||||||
.Spotlight-V100
|
|
||||||
.Trashes
|
|
||||||
Icon?
|
|
||||||
ehthumbs.db
|
|
||||||
Thumbs.db
|
|
||||||
.directory
|
|
||||||
|
|
||||||
# Tool specific files #
|
|
||||||
#######################
|
|
||||||
# vim
|
|
||||||
*~
|
|
||||||
*.swp
|
|
||||||
*.swo
|
|
||||||
# sublime text & textmate
|
|
||||||
*.sublime-*
|
|
||||||
*.stTheme.cache
|
|
||||||
*.tmlanguage.cache
|
|
||||||
*.tmPreferences.cache
|
|
||||||
# Eclipse
|
|
||||||
.settings/*
|
|
||||||
# JetBrains, aka PHPStorm, IntelliJ IDEA
|
|
||||||
.idea/*
|
|
||||||
# NetBeans
|
|
||||||
nbproject/*
|
|
||||||
# Visual Studio Code
|
|
||||||
.vscode
|
|
||||||
# Sass preprocessor
|
|
||||||
.sass-cache/
|
|
356
README.md
356
README.md
|
@ -1,347 +1,53 @@
|
||||||
# php-mysql
|
# php-libmysqldriver
|
||||||
|
|
||||||
This is a simple abstraction library for MySQL DML operations.
|
This library provides abstractions for parameter binding and result retrieval on MySQL(-like) databases in PHP. It is built on top of the PHP [`MySQL Improved`](https://www.php.net/manual/en/book.mysqli.php) extension.
|
||||||
|
|
||||||
For example:
|
## Install with Composer
|
||||||
```php
|
|
||||||
MySQL->from(string $table)
|
|
||||||
->where(?array ...$conditions)
|
|
||||||
->order(?array $order_by)
|
|
||||||
->limit(?int $limit = null, ?int $offset = null)
|
|
||||||
->select(string|array|null $columns = null): mysqli_result|bool;
|
|
||||||
```
|
|
||||||
which would be equivalent to the following in MySQL:
|
|
||||||
```sql
|
|
||||||
SELECT `columns` FROM `table` WHERE `filter` ORDER BY `order_by` LIMIT `limit`;
|
|
||||||
```
|
|
||||||
|
|
||||||
- All methods can be chained in any order (even multiple times) after a [`from()`](#from) as long as a [`select()`](#select), [`insert()`](#insert), [`update()`](#update), or [`delete()`](#delete) is the last method.
|
|
||||||
- Chaining the same method more than once will override its previous value. Passing `null` to any method that accepts it will unset its value completely.
|
|
||||||
|
|
||||||
## Install from composer
|
|
||||||
|
|
||||||
```
|
```
|
||||||
composer require vlw/mysql
|
composer require victorwesterlund/libmysqldriver
|
||||||
```
|
```
|
||||||
|
|
||||||
```php
|
```php
|
||||||
use vlw\MySQL\MySQL;
|
use libmysqldriver/MySQL;
|
||||||
```
|
```
|
||||||
|
|
||||||
> [!IMPORTANT]
|
## Usage
|
||||||
> This library requires the [`MySQL Improved`](https://www.php.net/manual/en/book.mysqli.php) extension and PHP 8.0 or newer.
|
|
||||||
|
|
||||||
# Example / Documentation
|
Connect to a MySQL database
|
||||||
|
|
||||||
Available statements
|
|
||||||
Statement|Method
|
|
||||||
--|--
|
|
||||||
`SELECT`|[`select()`](#select)
|
|
||||||
`UPDATE`|[`update()`](#update)
|
|
||||||
`INSERT`|[`insert()`](#insert)
|
|
||||||
`DELETE`|[`delete()`](#delete)
|
|
||||||
`WHERE`|[`where()`](#where)
|
|
||||||
`ORDER BY`|[`order()`](#order-by)
|
|
||||||
`LIMIT`|[`limit()`](#limit)
|
|
||||||
|
|
||||||
----
|
|
||||||
|
|
||||||
`Example table name: beverages`
|
|
||||||
id|beverage_type|beverage_name|beverage_size
|
|
||||||
--|--|--|--
|
|
||||||
0|coffee|cappuccino|10
|
|
||||||
1|coffee|black|15
|
|
||||||
2|tea|green|10
|
|
||||||
3|tea|black|15
|
|
||||||
|
|
||||||
```php
|
```php
|
||||||
use vlw\MySQL\MySQL;
|
use libysqldriver/MySQL;
|
||||||
|
|
||||||
// Pass through: https://www.php.net/manual/en/mysqli.construct.php
|
$db = new MySQL(
|
||||||
$db = new MySQL($host, $user, $pass, $db);
|
"localhost:3306",
|
||||||
|
"username",
|
||||||
|
"password",
|
||||||
|
"database"
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
All executor methods [`select()`](#select), [`update()`](#update), and [`insert()`](#insert) will return a [`mysqli_result`](https://www.php.net/manual/en/class.mysqli-result.php) object or boolean.
|
Return matching rows from query (array of arrays)
|
||||||
|
|
||||||
# FROM
|
|
||||||
|
|
||||||
```php
|
```php
|
||||||
MySQL->from(
|
$sql = "SELECT foo FROM table WHERE bar = ? AND biz = ?;
|
||||||
string $table
|
|
||||||
): self;
|
|
||||||
```
|
|
||||||
|
|
||||||
All queries start by chaining the `from(string $table)` method. This will define which database table the current query should be executed on.
|
$response = $db->return_array($sql, [
|
||||||
|
"parameter_1",
|
||||||
*Example:*
|
"parameter_2
|
||||||
```php
|
|
||||||
MySQL->from("beverages")->select("beverage_type");
|
|
||||||
```
|
|
||||||
|
|
||||||
# SELECT
|
|
||||||
|
|
||||||
Chain `MySQL->select()` anywhere after a [`MySQL->from()`](#from) to retrieve columns from a database table.
|
|
||||||
|
|
||||||
Pass an associative array of strings, CSV string, or null to this method to filter columns.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->select(
|
|
||||||
string|array|null $columns
|
|
||||||
): mysqli_result|bool;
|
|
||||||
```
|
|
||||||
|
|
||||||
In most cases you probably want to select with a constraint. Chain the [`where()`](#where) method before `select()` to filter the query
|
|
||||||
|
|
||||||
### Example
|
|
||||||
```php
|
|
||||||
$`beverages` = MySQL->from("beverages")->select(["beverage_name", "beverage_size"]); // SELECT `beverage_name`, `beverage_size` FROM beverages
|
|
||||||
```
|
|
||||||
```
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"beverage_name" => "cappuccino",
|
|
||||||
"beverage_size" => 10
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"beverage_name" => "black",
|
|
||||||
"beverage_size" => 15
|
|
||||||
],
|
|
||||||
// ...etc
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
# INSERT
|
|
||||||
|
|
||||||
Chain `MySQL->insert()` anywhere after a [`MySQL->from()`](#from) to append a new row to a database table.
|
|
||||||
|
|
||||||
Passing a sequential array to `insert()` will assume that you wish to insert data for all defined columns in the table. Pass an associative array of `[column_name => value]` to INSERT data for specific columns (assuming the other columns have a [DEFAULT](https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html) value defined).
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->insert(
|
|
||||||
// Array of values to INSERT
|
|
||||||
array $values
|
|
||||||
): bool
|
|
||||||
// Returns true if row was inserted
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->from("beverages")->insert([
|
|
||||||
null,
|
|
||||||
"coffee",
|
|
||||||
"latte",
|
|
||||||
10
|
|
||||||
]);
|
|
||||||
// INSERT INTO `beverages` VALUES (null, "coffee", "latte", 10);
|
|
||||||
```
|
|
||||||
```
|
|
||||||
true
|
|
||||||
```
|
|
||||||
|
|
||||||
# DELETE
|
|
||||||
|
|
||||||
Chain `MySQL->delete()` anywhere after a [`MySQL->from()`](#from) to remove a row or rows from the a database table.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->delete(
|
|
||||||
array ...$conditions
|
|
||||||
): bool
|
|
||||||
// Returns true if at least one row was deleted
|
|
||||||
```
|
|
||||||
|
|
||||||
This method takes at least one [`MySQL->where()`](#where)-syntaxed argument to determine which row or rows to delete. Refer to the [`MySQL->where()`](#where) section for more information.
|
|
||||||
|
|
||||||
#### Example
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->from("beverages")->delete([
|
|
||||||
"beverage_name" => "coffee",
|
|
||||||
]);
|
|
||||||
// DELETE FROM `beverages` WHERE `beverage_name` = "coffee";
|
|
||||||
```
|
|
||||||
```
|
|
||||||
true
|
|
||||||
```
|
|
||||||
|
|
||||||
# UPDATE
|
|
||||||
|
|
||||||
Chain `MySQL->update()` anywhere after a [`MySQL->from()`](#from) to modify existing rows in a database table.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->update(
|
|
||||||
// Key, value array of column names and values to update
|
|
||||||
array $fields,
|
|
||||||
): mysqli_result|bool;
|
|
||||||
// Returns true if at least 1 row was changed
|
|
||||||
```
|
|
||||||
|
|
||||||
### Example
|
|
||||||
```php
|
|
||||||
MySQL->from("beverages")->update(["beverage_size" => 10]); // UPDATE `beverages` SET `beverage_size` = 10
|
|
||||||
```
|
|
||||||
```php
|
|
||||||
true
|
|
||||||
```
|
|
||||||
|
|
||||||
In most cases you probably want to UPDATE against a constaint. Chain a [`where()`](#where) method before [`MySQL->update()`](#update) to set constraints
|
|
||||||
|
|
||||||
|
|
||||||
# WHERE
|
|
||||||
|
|
||||||
Filter a [`MySQL->select()`](#select) or [`MySQL->update()`](#update) method by chaining the `MySQL->where()` method anywhere before it. The [`MySQL->delete()`](#delete) executor method also uses the same syntax for its arguments.
|
|
||||||
|
|
||||||
Each key, value pair will be `AND` constrained against each other.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->where(
|
|
||||||
?array ...$conditions
|
|
||||||
): self;
|
|
||||||
```
|
|
||||||
|
|
||||||
### Example
|
|
||||||
```php
|
|
||||||
$coffee = MySQL->from("beverages")->where(["beverage_type" => "coffee"])->select(["beverage_name", "beverage_size"]); // SELECT `beverage_name`, `beverage_size` FROM `beverages` WHERE (`beverage_type` = "coffee");
|
|
||||||
```
|
|
||||||
```php
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"beverage_name" => "cappuccino",
|
|
||||||
"beverage_size" => 10
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"beverage_name" => "black",
|
|
||||||
"beverage_size" => 15
|
|
||||||
]
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Capture groups
|
|
||||||
|
|
||||||
### AND
|
|
||||||
|
|
||||||
Add additional key value pairs to an array passed to `where()` and they will all be compared as AND with each other.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->where([
|
|
||||||
"beverage_type" => "coffee",
|
|
||||||
"beverage_size" => 15
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
```sql
|
|
||||||
WHERE (`beverage_type` = 'coffee' AND `beverage_size` = 15)
|
|
||||||
```
|
|
||||||
|
|
||||||
### OR
|
|
||||||
|
|
||||||
Passing an additional array of key values as an argument will OR it with all other arrays passed.
|
|
||||||
|
|
||||||
```php
|
|
||||||
$filter1 = [
|
|
||||||
"beverage_type" => "coffee",
|
|
||||||
"beverage_size" => 15
|
|
||||||
];
|
];
|
||||||
|
|
||||||
$filter2 = [
|
// Example $response with two matching rows: [["hello"],["world"]]
|
||||||
"beverage_type" => "tea",
|
```
|
||||||
"beverage_name" => "black"
|
|
||||||
|
Return boolean if query matched at least one row, or if != `SELECT` query was sucessful
|
||||||
|
|
||||||
|
```php
|
||||||
|
$sql = "INSERT INTO table (foo, bar) VALUES (?, ?);
|
||||||
|
|
||||||
|
$response = $db->return_bool($sql, [
|
||||||
|
"baz",
|
||||||
|
"qux"
|
||||||
];
|
];
|
||||||
|
|
||||||
MySQL->where($filter1, $filter2, ...);
|
// Example $response if sucessful: true
|
||||||
```
|
|
||||||
```sql
|
|
||||||
WHERE (`beverage_type` = 'coffee' AND `beverage_size` = 15) OR (`beverage_type` = 'tea' AND `beverage_name` = 'black')
|
|
||||||
```
|
|
||||||
|
|
||||||
## Define custom operators
|
|
||||||
|
|
||||||
By default, all values in an the assoc array passed to `where()` will be treated as an `EQUALS` (=) operator.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->where(["column" => "euqals_this_value"]);
|
|
||||||
```
|
|
||||||
|
|
||||||
Setting the value of any key to another assoc array will allow for more "advanced" filtering by defining your own [`Operators`](https://github.com/VictorWesterlund/php-libmysqldriver/blob/master/src/Operators.php).
|
|
||||||
|
|
||||||
The key of this subarray can be any MySQL operator string, or the **->value** of any case in the [`Operators`](https://github.com/VictorWesterlund/php-libmysqldriver/blob/master/src/Operators.php) enum.
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->where([
|
|
||||||
"beverage_name" => [
|
|
||||||
Operators::LIKE->value => "%wildcard_contains%"
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
|
|
||||||
# ORDER BY
|
|
||||||
|
|
||||||
Chain the `MySQL->order()` method before a [`MySQL->select()`](#select) statement to order by a specific column
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->order(
|
|
||||||
?array $order_by
|
|
||||||
): self;
|
|
||||||
```
|
|
||||||
|
|
||||||
```php
|
|
||||||
$coffee = MySQL->from("beverages")->order(["beverage_name" => "ASC"])->select(["beverage_name", "beverage_size"]); // SELECT `beverage_name`, `beverage_size` FROM `beverages` ORDER BY `beverage_name` ASC
|
|
||||||
```
|
|
||||||
```php
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"beverage_name" => "tea",
|
|
||||||
"beverage_size" => 10
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"beverage_name" => "tea",
|
|
||||||
"beverage_size" => 15
|
|
||||||
],
|
|
||||||
// ...etc for "`beverage_name` = coffee"
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
# LIMIT
|
|
||||||
|
|
||||||
Chain the `limit()` method before a [`MySQL->select()`](#select) statement to limit the amount of columns returned
|
|
||||||
|
|
||||||
```php
|
|
||||||
MySQL->limit(
|
|
||||||
?int $limit,
|
|
||||||
?int $offset = null
|
|
||||||
): self;
|
|
||||||
```
|
|
||||||
|
|
||||||
## Passing a single integer argument
|
|
||||||
This will simply `LIMIT` the results returned to the integer passed
|
|
||||||
|
|
||||||
```php
|
|
||||||
$coffee = MySQL->from("beverages")->limit(1)->select(["beverage_name", "beverage_size"]); // SELECT `beverage_name`, `beverage_size` FROM `beverages` WHERE `beverage_type` = "coffee" LIMIT 1
|
|
||||||
```
|
|
||||||
```php
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"beverage_name" => "cappuccino",
|
|
||||||
"beverage_size" => 10
|
|
||||||
]
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Passing two integer arguments
|
|
||||||
This will `OFFSET` and `LIMIT` the results returned. The first argument will be the `LIMIT` and the second argument will be its `OFFSET`.
|
|
||||||
|
|
||||||
```php
|
|
||||||
$coffee = MySQL->from("beverages")->limit(3, 2)->select(["beverage_name", "beverage_size"]); // SELECT `beverage_name`, `beverage_size` FROM `beverages` LIMIT 3 OFFSET 2
|
|
||||||
```
|
|
||||||
```php
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"beverage_name" => "tea",
|
|
||||||
"beverage_size" => 10
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"beverage_name" => "tea",
|
|
||||||
"beverage_size" => 15
|
|
||||||
],
|
|
||||||
// ...etc
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
{
|
{
|
||||||
"name": "vlw/mysql",
|
"name": "victorwesterlund/libmysqldriver",
|
||||||
"description": "Abstraction library for common MySQL/MariaDB DML operations with php-mysqli",
|
"description": "Abstraction library for common mysqli features",
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-only",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "Victor Westerlund",
|
"name": "Victor Westerlund",
|
||||||
"email": "victor@vlw.se"
|
"email": "victor.vesterlund@gmail.com"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"minimum-stability": "dev",
|
"minimum-stability": "dev",
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"vlw\\MySQL\\": "src/"
|
"libmysqldriver\\": "src/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"require": {}
|
"require": {}
|
||||||
|
|
18
composer.lock
generated
18
composer.lock
generated
|
@ -1,18 +0,0 @@
|
||||||
{
|
|
||||||
"_readme": [
|
|
||||||
"This file locks the dependencies of your project to a known state",
|
|
||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
|
||||||
"This file is @generated automatically"
|
|
||||||
],
|
|
||||||
"content-hash": "aa59b0c90afdd92fd11d1cbc9352676c",
|
|
||||||
"packages": [],
|
|
||||||
"packages-dev": [],
|
|
||||||
"aliases": [],
|
|
||||||
"minimum-stability": "dev",
|
|
||||||
"stability-flags": [],
|
|
||||||
"prefer-stable": false,
|
|
||||||
"prefer-lowest": false,
|
|
||||||
"platform": [],
|
|
||||||
"platform-dev": [],
|
|
||||||
"plugin-api-version": "2.0.0"
|
|
||||||
}
|
|
352
src/MySQL.php
352
src/MySQL.php
|
@ -1,286 +1,120 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace vlw\MySQL;
|
namespace libmysqldriver;
|
||||||
|
|
||||||
use Exception;
|
class MySQL extends \mysqli {
|
||||||
|
function __construct(
|
||||||
use mysqli;
|
// From: https://www.php.net/manual/en/mysqli.construct.php
|
||||||
use mysqli_stmt;
|
string|null $host = null,
|
||||||
use mysqli_result;
|
string|null $user = null,
|
||||||
|
string|null $pass = null,
|
||||||
use vlw\MySQL\Order;
|
string|null $db = null
|
||||||
use vlw\MySQL\Operators;
|
) {
|
||||||
|
parent::__construct($host, $user, $pass, $db);
|
||||||
require_once "Order.php";
|
|
||||||
require_once "Operators.php";
|
|
||||||
|
|
||||||
// Interface for MySQL_Driver with abstractions for data manipulation
|
|
||||||
class MySQL extends mysqli {
|
|
||||||
public ?array $columns = null;
|
|
||||||
|
|
||||||
protected string $table;
|
|
||||||
protected ?string $limit = null;
|
|
||||||
protected ?string $order_by = null;
|
|
||||||
protected array $filter_columns = [];
|
|
||||||
protected array $filter_values = [];
|
|
||||||
protected ?string $filter_sql = null;
|
|
||||||
|
|
||||||
// Pass constructor arguments to driver
|
|
||||||
function __construct() {
|
|
||||||
parent::__construct(...func_get_args());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
// Bind SQL statements
|
||||||
# Helper methods
|
private function bind_params(\mysqli_stmt &$stmt, mixed $params) {
|
||||||
*/
|
// Make single-value, non-array, param an array with length of 1
|
||||||
|
if (gettype($params) !== "array") {
|
||||||
private function throw_if_no_table() {
|
$params = [$params];
|
||||||
if (!isset($this->table)) {
|
|
||||||
throw new Exception("No table name defined");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Coerce input to single dimensional array
|
|
||||||
private static function to_list_array(mixed $input): array {
|
|
||||||
return array_values(is_array($input) ? $input : [$input]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert value to MySQL tinyint
|
|
||||||
private static function filter_boolean(mixed $value): int {
|
|
||||||
return (int) filter_var($value, FILTER_VALIDATE_BOOLEAN);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert all boolean type values to tinyints in array
|
|
||||||
private static function filter_booleans(array $values): array {
|
|
||||||
return array_map(fn(mixed $v): mixed => gettype($v) === "boolean" ? self::filter_boolean($v) : $v, $values);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function array_wrap_accents(array $input): array {
|
|
||||||
return array_map(fn(mixed $v): string => "`{$v}`", $input);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
# Definers
|
|
||||||
These methods are used to build an SQL query by chaining methods together.
|
|
||||||
Defined parameters will then be executed by an Executer method.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Use the following table name
|
|
||||||
public function from(string $table): self {
|
|
||||||
// Reset all definers when a new query begins
|
|
||||||
$this->where();
|
|
||||||
$this->limit();
|
|
||||||
$this->order();
|
|
||||||
|
|
||||||
$this->table = $table;
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[\Deprecated(
|
|
||||||
message: "use MySQL->from() instead",
|
|
||||||
since: "3.5.7",
|
|
||||||
)]
|
|
||||||
public function for(string $table): self {
|
|
||||||
return $this->from($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a WHERE statement from filters
|
|
||||||
public function where(?array ...$conditions): self {
|
|
||||||
// Unset filters if null was passed
|
|
||||||
if ($conditions === null) {
|
|
||||||
$this->filter_sql = null;
|
|
||||||
$this->filter_columns = null;
|
|
||||||
$this->filter_values = null;
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$values = [];
|
// Concatenated string with types for each param
|
||||||
$filters = [];
|
$types = "";
|
||||||
|
|
||||||
// Group each condition into an AND block
|
if (!empty($params)) {
|
||||||
foreach ($conditions as $condition) {
|
// Convert PHP primitve to SQL primitive for params
|
||||||
$filter = [];
|
foreach ($params as $param) {
|
||||||
|
switch (gettype($param)) {
|
||||||
|
case "integer":
|
||||||
|
case "double":
|
||||||
|
case "boolean":
|
||||||
|
$types .= "i";
|
||||||
|
break;
|
||||||
|
|
||||||
// Move along if the condition is empty
|
case "string":
|
||||||
if (empty($condition)) {
|
case "array":
|
||||||
continue;
|
case "object":
|
||||||
}
|
$types .= "s";
|
||||||
|
break;
|
||||||
|
|
||||||
// Create SQL string and append values to array for prepared statement
|
default:
|
||||||
foreach ($condition as $col => $operation) {
|
$types .= "b";
|
||||||
$this->filter_columns[] = $col;
|
break;
|
||||||
|
|
||||||
// Assume we want an equals comparison if value is not an array
|
|
||||||
if (!is_array($operation)) {
|
|
||||||
$operation = [Operators::EQUALS->value => $operation];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve all operator enum values in inner array
|
|
||||||
foreach ($operation as $operator => $value) {
|
|
||||||
// Null values have special syntax
|
|
||||||
if (is_null($value)) {
|
|
||||||
// Treat anything that isn't an equals operator as falsy
|
|
||||||
if ($operator !== Operators::EQUALS->value) {
|
|
||||||
$filter[] = "`{$col}` IS NOT NULL";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$filter[] = "`{$col}` IS NULL";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create SQL for prepared statement
|
|
||||||
$filter[] = "`{$col}` {$operator} ?";
|
|
||||||
|
|
||||||
// Append value to array with all other values
|
|
||||||
$values[] = $value;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// AND together all conditions into a group
|
$stmt->bind_param($types, ...$params);
|
||||||
$filters[] = "(" . implode(" AND ", $filter) . ")";
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do nothing if no filters were set
|
// Execute statement and get affected rows
|
||||||
if (empty($filters)) {
|
$query = $stmt->execute();
|
||||||
return $this;
|
$res = $stmt->get_result();
|
||||||
|
|
||||||
|
// Return true if an INSERT, UPDATE or DELETE was sucessful (no rows returned)
|
||||||
|
if (!empty($query) && empty($res)) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// OR all filter groups
|
// Return mysqli_result object
|
||||||
$this->filter_sql = implode(" OR ", $filters);
|
return $res;
|
||||||
// Set values property
|
|
||||||
$this->filter_values = $values;
|
|
||||||
|
|
||||||
return $this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SQL LIMIT string
|
/* ---- */
|
||||||
public function limit(?int $limit = null, ?int $offset = null): self {
|
|
||||||
// Unset row limit if null was passed
|
// Create comma separated list (CSV) from array
|
||||||
if ($limit === null) {
|
private static function csv(array $values): string {
|
||||||
$this->limit = null;
|
return implode(",", $values);
|
||||||
return $this;
|
}
|
||||||
|
|
||||||
|
// Create CSV from columns
|
||||||
|
public static function columns(array|string $columns): string {
|
||||||
|
return is_array($columns)
|
||||||
|
? (__CLASS__)::csv($columns)
|
||||||
|
: $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return CSV of '?' for use with prepared statements
|
||||||
|
public static function values(array|string $values): string {
|
||||||
|
return is_array($values)
|
||||||
|
? (__CLASS__)::csv(array_fill(0, count($values), "?"))
|
||||||
|
: "?";
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- */
|
||||||
|
|
||||||
|
// Get result as an associative array
|
||||||
|
public function return_array(string $sql, mixed $params = null): array {
|
||||||
|
$query = $this->run_query($sql, $params);
|
||||||
|
|
||||||
|
$res = [];
|
||||||
|
while ($data = $query->fetch_assoc()) {
|
||||||
|
$res[] = $data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Coerce offset to zero if no offset is defined
|
return $res;
|
||||||
$offset = $offset ?? 0;
|
|
||||||
|
|
||||||
// Set limit and offset as SQL CSV
|
|
||||||
$this->limit = "{$offset},{$limit}";
|
|
||||||
return $this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return SQL SORT BY string from assoc array of columns and direction
|
// Get only whether a query was sucessful or not
|
||||||
public function order(?array $order_by = null): self {
|
public function return_bool(string $sql, mixed $params = null): bool {
|
||||||
// Unset row order by if null was passed
|
$query = $this->run_query($sql, $params);
|
||||||
if ($order_by === null) {
|
|
||||||
$this->order_by = null;
|
// Return query if it's already a boolean
|
||||||
return $this;
|
if (gettype($query) === "boolean") {
|
||||||
|
return $query;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assign Order Enum entries from array of arrays<Order|string>
|
return $query->num_rows > 0 ? true : false;
|
||||||
$orders = array_map(fn(Order|string $order): Order => $order instanceof Order ? $order : Order::tryFrom($order), array_values($order_by));
|
|
||||||
// Create CSV string with Prepared Statement abbreviations from length of fields array.
|
|
||||||
$sql = array_map(fn(string $column, Order|string $order): string => "`{$column}` " . $order->value, array_keys($order_by), $orders);
|
|
||||||
|
|
||||||
$this->order_by = implode(",", $sql);
|
|
||||||
return $this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
# Executors
|
|
||||||
These methods execute various statements that each return a mysqli_result
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Create Prepared Statament for SELECT with optional WHERE filters
|
|
||||||
public function select(array|string|null $columns = null): mysqli_result|bool {
|
|
||||||
$this->throw_if_no_table();
|
|
||||||
|
|
||||||
// Create array of columns from CSV
|
|
||||||
$this->columns = is_array($columns) || is_null($columns) ? $columns : explode(",", $columns);
|
|
||||||
|
|
||||||
// Create CSV from columns or default to SQL NULL as a string
|
|
||||||
$columns_sql = $this->columns ? implode(",", self::array_wrap_accents($this->columns)) : "NULL";
|
|
||||||
|
|
||||||
// Create LIMIT statement if argument is defined
|
|
||||||
$limit_sql = !is_null($this->limit) ? " LIMIT {$this->limit}" : "";
|
|
||||||
|
|
||||||
// Create ORDER BY statement if argument is defined
|
|
||||||
$order_by_sql = !is_null($this->order_by) ? " ORDER BY {$this->order_by}" : "";
|
|
||||||
|
|
||||||
// Get array of SQL WHERE string and filter values
|
|
||||||
$filter_sql = !is_null($this->filter_sql) ? " WHERE {$this->filter_sql}" : "";
|
|
||||||
|
|
||||||
// Interpolate components into an SQL SELECT statmenet and execute
|
|
||||||
$sql = "SELECT {$columns_sql} FROM `{$this->table}`{$filter_sql}{$order_by_sql}{$limit_sql}";
|
|
||||||
// Return mysqli_response of matched rows
|
|
||||||
return $this->execute_query($sql, self::to_list_array($this->filter_values));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create Prepared Statement for UPDATE using PRIMARY KEY as anchor
|
|
||||||
public function update(array $entity): mysqli_result|bool {
|
|
||||||
$this->throw_if_no_table();
|
|
||||||
|
|
||||||
// Create CSV string with Prepared Statement abbreviations from length of fields array.
|
|
||||||
$changes = array_map(fn($column) => "`{$column}` = ?", array_keys($entity));
|
|
||||||
$changes = implode(",", $changes);
|
|
||||||
|
|
||||||
// Get array of SQL WHERE string and filter values
|
|
||||||
$filter_sql = !is_null($this->filter_sql) ? " WHERE {$this->filter_sql}" : "";
|
|
||||||
|
|
||||||
// Get values from entity and convert booleans to tinyint
|
|
||||||
$values = self::filter_booleans(array_values($entity));
|
|
||||||
|
|
||||||
// Append values to filter property if where() was chained
|
|
||||||
if ($this->filter_values) {
|
|
||||||
array_push($values, ...$this->filter_values);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Interpolate components into an SQL UPDATE statement and execute
|
|
||||||
$sql = "UPDATE `{$this->table}` SET {$changes} {$filter_sql}";
|
|
||||||
return $this->execute_query($sql, self::to_list_array($values));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create Prepared Statemt for INSERT
|
|
||||||
public function insert(array $values): mysqli_result|bool {
|
|
||||||
$this->throw_if_no_table();
|
|
||||||
|
|
||||||
/*
|
|
||||||
Use array keys from $values as columns to insert if array is associative.
|
|
||||||
Treat statement as an all-columns INSERT if the $values array is sequential.
|
|
||||||
*/
|
|
||||||
$columns = !array_is_list($values) ? "(" . implode(",", array_keys($values)) . ")" : "";
|
|
||||||
|
|
||||||
// Convert booleans to tinyint
|
|
||||||
$values = self::filter_booleans($values);
|
|
||||||
|
|
||||||
// Create CSV string with Prepared Statement abbreviatons from length of fields array.
|
|
||||||
$values_stmt = implode(",", array_fill(0, count($values), "?"));
|
|
||||||
|
|
||||||
// Interpolate components into an SQL INSERT statement and execute
|
|
||||||
$sql = "INSERT INTO `{$this->table}` {$columns} VALUES ({$values_stmt})";
|
|
||||||
return $this->execute_query($sql, self::to_list_array($values));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create Prepared Statemente for DELETE with WHERE condition(s)
|
|
||||||
public function delete(array ...$conditions): mysqli_result|bool {
|
|
||||||
$this->throw_if_no_table();
|
|
||||||
|
|
||||||
// Set DELETE WHERE conditions from arguments
|
|
||||||
if ($conditions) {
|
|
||||||
$this->where(...$conditions);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get array of SQL WHERE string and filter values
|
|
||||||
$filter_sql = !is_null($this->filter_sql) ? " WHERE {$this->filter_sql}" : "";
|
|
||||||
|
|
||||||
$sql = "DELETE FROM `{$this->table}`{$filter_sql}";
|
|
||||||
return $this->execute_query($sql, self::to_list_array($this->filter_values));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute SQL query with optional prepared statement and return mysqli_result
|
|
||||||
public function exec(string $sql, mixed $params = null): mysqli_result {
|
|
||||||
return $this->execute_query($sql, self::to_list_array($params));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,46 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace vlw\MySQL;
|
|
||||||
|
|
||||||
enum Operators: string {
|
|
||||||
// Logical
|
|
||||||
case ALL = "ALL";
|
|
||||||
case AND = "AND";
|
|
||||||
case ANY = "ANY";
|
|
||||||
case BETWEEN = "BETWEEN";
|
|
||||||
case EXISTS = "EXISTS";
|
|
||||||
case IN = "IN";
|
|
||||||
case LIKE = "LIKE";
|
|
||||||
case NOT = "NOT";
|
|
||||||
case OR = "OR";
|
|
||||||
case SOME = "SOME";
|
|
||||||
|
|
||||||
// Comparison
|
|
||||||
case EQUALS = "=";
|
|
||||||
case GT = ">";
|
|
||||||
case LT = "<";
|
|
||||||
case GTE = ">=";
|
|
||||||
case LTE = "<=";
|
|
||||||
case NOTE = "<>";
|
|
||||||
|
|
||||||
// Arithmetic
|
|
||||||
case ADD = "+";
|
|
||||||
case SUBTRACT = "-";
|
|
||||||
case MULTIPLY = "*";
|
|
||||||
case DIVIDE = "/";
|
|
||||||
case MODULO = "%";
|
|
||||||
|
|
||||||
// Bitwise
|
|
||||||
case BS_AND = "&";
|
|
||||||
case BS_OR = "|";
|
|
||||||
case BS_XOR = "^";
|
|
||||||
|
|
||||||
// Compound
|
|
||||||
case ADDE = "+=";
|
|
||||||
case SUBE = "-=";
|
|
||||||
case DIVE = "/=";
|
|
||||||
case MODE = "%=";
|
|
||||||
case BS_ANDE = "&=";
|
|
||||||
case BS_ORE = "|*=";
|
|
||||||
case BS_XORE = "^-=";
|
|
||||||
}
|
|
|
@ -1,8 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
namespace vlw\MySQL;
|
|
||||||
|
|
||||||
enum Order: string {
|
|
||||||
case ASC = "ASC";
|
|
||||||
case DESC = "DESC";
|
|
||||||
}
|
|
Loading…
Add table
Reference in a new issue