Skip to content

Commit

Permalink
Update README
Browse files Browse the repository at this point in the history
  • Loading branch information
ratajs committed Jul 15, 2024
1 parent f8a47e0 commit 41dfb1e
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 159 deletions.
288 changes: 139 additions & 149 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,95 +1,82 @@
# SuperSQL
SuperSQL is an easy-to-use powerful SQL query builder for SQLite and MySQL.
SuperSQL is an easy-to-use, yet powerful SQL query builder for SQLite and MySQL.

## Requirements
* PHP 5.6+
* PHP 7+
* PDO SQLite / MySQL driver

## Setup
* Download the <em>ssql.php</em> file ([https://raw.githubusercontent.com/ratajs/SuperSQL/2.2/ssql.php](https://raw.githubusercontent.com/ratajs/SuperSQL/2.2/ssql.php))
* Download the <em>ssql.php</em> file ([https://raw.githubusercontent.com/ratajs/SuperSQL/2.3/ssql.php](https://raw.githubusercontent.com/ratajs/SuperSQL/2.3/ssql.php))
* Include the file with `include` / `require`

## Examples
Let’s have a table <strong>users</strong> with 5 columns: `uid`, `username`, `password`, `sign_up_time` and `nickname`
Let’s have a table <strong>users</strong> with 5 columns: `uid`, `username`, `password`, `sign_up_time` and `nickname`

```php
<?php
include "ssql.php";

//Connect with new Ssql($host[, $user[, $password[, $database]]])
$ssql = new Ssql("localhost", "root", "root", "db"); // MySQL

//Connect to SQLite with just the first parameter
$ssql = new Ssql("db.sqlite3");

//To execute raw SQL query use $ssql->q($q[, $a]), FETCH_ALL returns an array of rows, FETCH_OBJECT and FETCH_ARRAY return one row per call
$ssql->q("SELECT * FROM users")->fetch(SQ::FETCH_ALL);

//You can use wildcards for escaping
$ssql->q("SELECT * FROM users WHERE `username`=%0 OR `nickname`=%1", [$name, $nick])->fetch();

//You can set the object‐wide $debug property to print all queries before being executed
$ssql->debug = true;

//You can use queries as methods
$ssql->getUser = "SELECT * FROM users WHERE `username`=%0 OR `nickname`=%1";
$user = $ssql->getUser($name, $nick)->fetch();

//For simple requests use $ssql->read($table[, $cond][, $flags])
//Read function uses FETCH_SMART as default (FETCH_OBJECT for one row, FETCH_ALL for more), so you need to use the FETCH_ALL flag to return an array even when there is only one result
$users = $ssql->read("users", SQ::FETCH_ALL);
$user = $ssql->read("users", ['uid' => $id]);

//You can use the DEBUG flag to print this query before execution
$user = $ssql->read("users", ['uid' => $id], SQ::DEBUG);

//You can use more conditions
$user = $ssql->read("users", ['username' => $name, 'password' => $pass]);

//You can use the COND_OR flag for OR operator instead of AND
$user = $ssql->read("users", ['username' => $name, 'nickname' => $nick], SQ::FETCH_ALL | SQ::COND_OR)[0];

//You can use custom conditions
$users = $ssql->read("users", "`sign_up_time` > " . bcsub(time(), 3600));

//You can use more of them
$users = $ssql->read("users", ["`sign_up_time` > " . bcsub(time(), 3600), "`nickname` IS NOT NULL"], SQ::FETCH_ALL);

//For more complicated requests use $ssql->select($table[, $order[, $cols[, $limit[, $flags]]]]), you can use array keys for aliases
$users = $ssql->select("users", "sign_up_time", ['id' => "uid", 'name' => "username", "sign_up_time", "nickname"], NULL, SQ::ORDER_DESC)->fetch(SQ::FETCH_ALL);

//Or $ssql->selectWhere($table, $cond[, $order[, $cols[, $limit[, $flags]]]])
$user = $ssql->selectWhere("users", ['uid' => $id], "name", ['id' => "uid", 'name' => "username", "sign_up_time", 'nick' => "nickname"])->fetch();

//To quickly display tables use ->dump()
$ssql->select("users")->dump();

//Insert with $ssql->insert($table, $values[, $flags])
$ssql->insert("users", [$id, $name, $pass, time(), NULL]);

//You can use array keys as col names
$ssql->insert("users", ['username' => $name, 'password' => $pass, 'sign_up_time' => time()]);

//You can use INSERT_RETURN_ID flag for returning the first auto increment col value (depends on the database type)
$id = $ssql->insert("users", ['username' => $name, 'password' => $pass, 'sign_up_time' => time()], SQ::INSERT_RETURN_ID);

//Use $ssql->update($table, $cond, $values[, $flags]) to update rows
$ssql->update("users", ['id' => $id], ['nickname' => $nick]);

//You can delete rows with $ssql->delete($table, $cond[, $flags])
$ssql->delete("users", ['id' => $id]);

//You can use $ssql->put($table, $data[, $cond][, $flags]) for inserting, updating and deleting as well
//Insert
$ssql->put("users", [$id, $name, $pass, time(), NULL]);
$ssql->put("users", ['username' => $name, 'password' => $pass, 'sign_up_time' => time()], SQ::INSERT_RETURN_ID);
//Update
$ssql->put("users", ['nickname' => $nick], ['id' => $id]);
//Delete
$ssql->put("users", NULL, ['id' => $id]);

//Use $ssql->truncate($table[, $flags]) to delete all rows in a table
$ssql->truncate("users");
include "ssql.php";

//Connect to MySQL with new Ssql($host[, $user[, $password[, $database]]])
$ssql = new Ssql("localhost", "root", "root", "db");

//Connect to SQLite with just the first argument
$ssql = new Ssql("db.sqlite3");

//Use $ssql->q($q[, $a]) to execute a raw SQL query
$ssql->q("SELECT * FROM `users`");

//You can use wildcards for escaping
$ssql->q("SELECT * FROM `users` WHERE `username`=%0 OR `nickname`=%1", [$name, $nick]);

//You can use queries as methods
$ssql->getUser = "SELECT * FROM `users` WHERE `username` = '%0' OR `nickname` = '%1'";
$user = $ssql->getUser($name, $nick);

//Use $ssql->read($table[, $cond][, $flags]) for simple reading
$users = $ssql->read("users"); // Access the username of a specific user with $users[$index]->username
$users = $users->data(); // If you need a raw array, for example for json_encode($users)
$user = $ssql->read("users", ['uid' => $id]); // You can access the username with $user->username if only one result is returned

//You can use the DEBUG flag to print this query before execution
$user = $ssql->read("users", ['uid' => $id], SQ::DEBUG);

//Or you can set the object‐wide $debug property to print all queries
$ssql->debug = true;

//You can use more conditions
$user = $ssql->read("users", ['username' => $name, 'password' => $pass]);

//You can use the COND_OR flag to use the OR operator instead of AND
$user = $ssql->read("users", ['username' => $name, 'nickname' => $nick], SQ::COND_OR)[0];

//You can use custom conditions
$users = $ssql->read("users", "`sign_up_time` > " . bcsub(time(), 3600));

//You can use more of them
$users = $ssql->read("users", ["`sign_up_time` > " . bcsub(time(), 3600), "`nickname` IS NOT NULL"]);

//Use $ssql->get($table[, $options][, $flags]) for more complex data retrieval
$users = $ssql->get("users", ['order' => "sign_up_time", 'cols' => ['id' => "uid", 'name' => "username", "sign_up_time", "nickname"], 'limit' => 10], SQ::ORDER_DESC);
$user = $ssql->get("users", ['cond' => ['uid' => $id], 'order' => "name", 'cols' => ['id' => "uid", 'name' => "username", "sign_up_time", 'nick' => "nickname"]]);

//You can print the result of a ->read() or ->get() call as an HTML table
print $ssql->read("users");

//Insert with $ssql->put($table, $values[, $flags])
$ssql->put("users", [$id, $name, $pass, time(), NULL]);

//You can use array keys as col names
$ssql->put("users", ['username' => $name, 'password' => $pass, 'sign_up_time' => time()]);

//You can use INSERT_RETURN_ID flag for returning the first auto increment col value (depends on the database type)
$id = $ssql->put("users", ['username' => $name, 'password' => $pass, 'sign_up_time' => time()], SQ::INSERT_RETURN_ID);

//Use $ssql->put($table, $values, $cond[, $flags]) to update rows
$ssql->put("users", ['nickname' => $nick], ['uid' => $id]);

//You can delete rows by supplying NULL to the $values argument
$ssql->put("users", NULL, ['uid' => $id]);
$ssql->put("users", NULL); //Delete all users
?>
```

Expand All @@ -104,81 +91,84 @@ Here is list of all SuperSQL flags:
* <b>INSERT_RETURN_ID</b>
* <b>COND_AND</b>
* <b>COND_OR</b>
* <b>FETCH_OBJECT</b>
* <b>FETCH_ARRAY</b>
* <b>FETCH_ALL</b>
* <b>FETCH_SMART</b>
* <b>CASE_INSENSITIVE</b>
* <b>NO_ERROR</b>
* <b>DEBUG</b>

## More examples

```php
<?php
//To use the same database in more projects you can extend the Ssql class
class mySsql extends Ssql {
protected $host = "localhost";
protected $user = "root";
protected $password = "root";
protected $db = "db"; //Optional
};
//And then create an instance
$ssql = new mySsql();
//If $db is not set, you can set it afterwards
$ssql->changeDb("newDB");


//Join


//Use $ssql->selectJoin($table, $join, $on[, $order[, $cols[, $limit[, $flags]]]]) to execute a JOIN command
$result = $ssql->selectJoin("users", "messages", ['from_user' => 'uid'], "time", "*", 5, SQ::ORDER_DESC)->fetch(SQ::FETCH_ALL);
//Use JOIN_LEFT, JOIN_RIGHT and JOIN_FULL flags to other types of JOIN

//To combine JOIN and WHERE use $ssql->selectJoinWhere($table, $join, $on, $cond[, $order[, $cols[, $limit[, $flags]]]])
$result = $ssql->selectJoinWhere("users", "messages", ['from_user' => 'uid'], ['from_user' => $uid])->fetch(SQ::FETCH_ALL);



//Table creation and deletion


//For basic table creation use $ssql->createTable($table, $params[, $primary[, $flags]])
$ssql->createTable("myTable", [
'number' => [ // Column name
'type' => "int", // Column type
'NULL' => false // NULL
],
'text' => [
'type' => "varchar",
'length' => 64, // Max length
'NULL' => true
]
], "number");

//Use $ssql->deleteTable($table[, $flags]) to delete a table
$ssql->deleteTable("myTable");

//To see a list of all tables in your database use $ssql->tableList([$flags])
print_r($ssql->tableList());


//Advanced conditions


//You can use more advanced conditions with $ssql->cond(), this will select users that have the same username and nickname signed up in the last hour
$ssql->read("users", $ssql->cond()->eq("username", "nickname")->gte("sign_up_time", time() - 3600));

//Use arrays to differentiate string values from column names and to specify more alternatives, the COND_OR flag is also supported
//This will select users that have username either "ratajs" or "admin" or that have nickname "RatajS"
$ssql->read("users", $ssql->cond()->eq("username", ["ratajs", "admin"])->eq("nickname", ["RatajS"], SQ::COND_OR));

//->not() negates the condition, this will select users with usernames other than admin
$ssql->read("users", $ssql->cond()->eq("username", ["admin"])->not());

//You can also pass another condition to it, this will select users that don’t have any nickname with username other than "admin" or "root".
$ssql->read("users", $ssql->cond()->eq("nickname", [""])->not($ssql->cond()->eq("username", ["admin", "root"])));

//Supported conditions: ->eq(), ->lt(), ->gt(), ->lte(), ->gte(), ->like(), ->between(), ->begins(), ->ends(), ->contains() and ->in()
//To use the same database in more projects you can extend the Ssql class
class mySsql extends Ssql {
protected $host = "localhost";
protected $user = "root";
protected $password = "root";
protected $db = "db"; //Optional
};
//And then create an instance
$ssql = new mySsql();
//If $db is not set, you can set it afterwards
$ssql->changeDb("newDB");


//Join


$result = $ssql->get("users", ['join' => "messages", 'on' => ['from_user' => 'uid'], 'order' => "time", 'limit' => 5], SQ::ORDER_DESC);
//Use JOIN_LEFT, JOIN_RIGHT and JOIN_FULL flags for other types of JOIN

$result = $ssql->get("users", ['join' => "messages", 'on' => ['from_user' => 'uid'], 'cond' => ['from_user' => $uid]]);



//Table creation and deletion


//For basic table creation use $ssql->createTable($table, $params[, $primary[, $flags]])
$ssql->createTable("myTable", [
'number' => [
'type' => "int",
'NULL' => false
],
'text' => [
'type' => "varchar",
'size' => 64,
'NULL' => true
]
], "number"); // Primary key

//Use $ssql->deleteTable($table[, $flags]) to delete a table
$ssql->deleteTable("myTable");

//To see a list of all tables in your database use $ssql->tableList([$flags])
print_r($ssql->tableList());


//Advanced conditions


//You can use more advanced conditions with $ssql->cond(), this will select users that have the same username and nickname signed up in the last hour
$ssql->read("users", $ssql->cond()->eq("username", "nickname")->gte("sign_up_time", time() - 3600));

//Use arrays to differentiate string values from column names and to specify more alternatives, the COND_OR flag is also supported
//This will select users that have username either "ratajs" or "admin" or that have nickname "RatajS"
$ssql->read("users", $ssql->cond()->eq("username", ["ratajs", "admin"])->eq("nickname", ["RatajS"], SQ::COND_OR));

//->not() negates the condition, this will select users with usernames other than admin
$ssql->read("users", $ssql->cond()->eq("username", ["admin"])->not());

//You can also pass another condition to it, this will select users that don’t have any nickname with username other than "admin" or "root".
$ssql->read("users", $ssql->cond()->eq("nickname", [""])->not($ssql->cond()->eq("username", ["admin", "root"])));

//Supported conditions: ->eq(), ->lt(), ->gt(), ->lte(), ->gte(), ->like(), ->between(), ->begins(), ->ends(), ->contains() and ->in()

//Transactions

$ssql->beginTransaction();

//...

$ssql->endTransaction(); //Or $ssql->rollBackTransaction()
?>
```
11 changes: 3 additions & 8 deletions ssql.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,9 @@ abstract class SQ {
const INSERT_RETURN_ID = 64;
const COND_AND = 128;
const COND_OR = 256;
const FETCH_OBJECT = 512;
const FETCH_ARRAY = 1024;
const FETCH_ALL = 2048;
const FETCH_SMART = 4096;
const FETCH_HTML = 8192;
const CASE_INSENSITIVE = 16384;
const NO_ERROR = 32768;
const DEBUG = 65536;
const CASE_INSENSITIVE = 512;
const NO_ERROR = 1024;
const DEBUG = 2048;

static function open(string $host = "", string $user = "", string $password = "", string $db = "", &$object = "return") {
if($object=="return")
Expand Down
4 changes: 2 additions & 2 deletions tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@
assert($r[0]->num==16);
assert($r[1]->num==48);

$ssql->q("UPDATE `table3` SET `table3_num` = \"%1\" WHERE `table3_id` = \"%0\"", "3", "42");
$ssql->q("UPDATE `table3` SET `table3_num` = '%1' WHERE `table3_id` = '%0'", "3", "42");
$r = $ssql->read("table3");
assert(count($r)==4);
assert($r[0]->table3_id==1);
Expand All @@ -537,7 +537,7 @@
assert(count($r)==1);
assert($r[0]->num==16);

$ssql->inc = "UPDATE `table3` SET `table3_num` = `table3_num` + 1 WHERE `table3_id` = %0";
$ssql->inc = "UPDATE `table3` SET `table3_num` = `table3_num` + 1 WHERE `table3_id` = '%0'";
$ssql->inc(4);
$r = $ssql->read("table3");
assert(count($r)==4);
Expand Down

0 comments on commit 41dfb1e

Please sign in to comment.