{"id":13810400,"url":"https://github.com/ThingEngineer/PHP-MySQLi-Database-Class","last_synced_at":"2025-05-14T10:33:20.656Z","repository":{"id":38419168,"uuid":"1017748","full_name":"ThingEngineer/PHP-MySQLi-Database-Class","owner":"ThingEngineer","description":"Wrapper for a PHP MySQL class, which utilizes MySQLi and prepared statements. ","archived":false,"fork":false,"pushed_at":"2024-06-28T12:18:09.000Z","size":656,"stargazers_count":3303,"open_issues_count":206,"forks_count":1348,"subscribers_count":263,"default_branch":"master","last_synced_at":"2025-05-13T17:13:23.811Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ThingEngineer.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-10-23T15:19:38.000Z","updated_at":"2025-05-13T11:58:52.000Z","dependencies_parsed_at":"2022-07-11T19:49:58.268Z","dependency_job_id":"a391faf2-440c-4320-ad5b-77642a060514","html_url":"https://github.com/ThingEngineer/PHP-MySQLi-Database-Class","commit_stats":{"total_commits":423,"total_committers":72,"mean_commits":5.875,"dds":"0.37825059101654845","last_synced_commit":"5159467ae081adbe96586e45e65a58c0fe7a32ce"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ThingEngineer%2FPHP-MySQLi-Database-Class","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ThingEngineer%2FPHP-MySQLi-Database-Class/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ThingEngineer%2FPHP-MySQLi-Database-Class/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ThingEngineer%2FPHP-MySQLi-Database-Class/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ThingEngineer","download_url":"https://codeload.github.com/ThingEngineer/PHP-MySQLi-Database-Class/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254121144,"owners_count":22018112,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T02:00:52.110Z","updated_at":"2025-05-14T10:33:20.587Z","avatar_url":"https://github.com/ThingEngineer.png","language":"PHP","readme":"MysqliDb -- Simple MySQLi wrapper and object mapper with prepared statements\n\u003chr\u003e\n\n### Table of Contents\n\n**[Initialization](#initialization)**  \n**[Objects mapping](#objects-mapping)**  \n**[Insert Query](#insert-query)**  \n**[Update Query](#update-query)**  \n**[Select Query](#select-query)**  \n**[Delete Query](#delete-query)**  \n**[Insert Data](#insert-data)**  \n**[Insert XML](#insert-xml)**  \n**[Pagination](#pagination)**  \n**[Running raw SQL queries](#running-raw-sql-queries)**  \n**[Query Keywords](#query-keywords)**  \n**[Where Conditions](#where--having-methods)**  \n**[Order Conditions](#ordering-method)**  \n**[Group Conditions](#grouping-method)**  \n**[Properties Sharing](#properties-sharing)**  \n**[Joining Tables](#join-method)**  \n**[Subqueries](#subqueries)**  \n**[EXISTS / NOT EXISTS condition](#exists--not-exists-condition)**  \n**[Has method](#has-method)**  \n**[Helper Methods](#helper-methods)**  \n**[Transaction Helpers](#transaction-helpers)**  \n**[Error Helpers](#error-helpers)**  \n**[Table Locking](#table-locking)**  \n\n## Support Me\n\nThis software is developed during my free time and I will be glad if somebody will support me.\n\nEveryone's time should be valuable, so please consider donating.\n\n[Donate with paypal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations\u0026business=a%2ebutenka%40gmail%2ecom\u0026lc=DO\u0026item_name=mysqlidb\u0026currency_code=USD\u0026bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)\n\n### Installation\nTo utilize this class, first import MysqliDb.php into your project, and require it.\n\n```php\nrequire_once ('MysqliDb.php');\n```\n\n### Installation with composer\nIt is also possible to install library via composer\n```\ncomposer require thingengineer/mysqli-database-class:dev-master\n```\n\n### Initialization\nSimple initialization with utf8 charset set by default:\n```php\n$db = new MysqliDb ('host', 'username', 'password', 'databaseName');\n```\n\nAdvanced initialization:\n```php\n$db = new MysqliDb (Array (\n                'host' =\u003e 'host',\n                'username' =\u003e 'username', \n                'password' =\u003e 'password',\n                'db'=\u003e 'databaseName',\n                'port' =\u003e 3306,\n                'prefix' =\u003e 'my_',\n                'charset' =\u003e 'utf8'));\n```\ntable prefix, port and database charset params are optional.\nIf no charset should be set charset, set it to null\n\nAlso it is possible to reuse already connected mysqli object:\n```php\n$mysqli = new mysqli ('host', 'username', 'password', 'databaseName');\n$db = new MysqliDb ($mysqli);\n```\n\nIf no table prefix were set during object creation its possible to set it later with a separate call:\n```php\n$db-\u003esetPrefix ('my_');\n```\n\nIf connection to mysql will be dropped Mysqlidb will try to automatically reconnect to the database once. \nTo disable this behavoir use\n```php\n$db-\u003eautoReconnect = false;\n```\n\nIf you need to get already created mysqliDb object from another class or function use\n```php\n    function init () {\n        // db staying private here\n        $db = new MysqliDb ('host', 'username', 'password', 'databaseName');\n    }\n    ...\n    function myfunc () {\n        // obtain db object created in init  ()\n        $db = MysqliDb::getInstance();\n        ...\n    }\n```\n\n### Multiple database connection\nIf you need to connect to multiple databases use following method:\n```php\n$db-\u003eaddConnection('slave', Array (\n                'host' =\u003e 'host',\n                'username' =\u003e 'username',\n                'password' =\u003e 'password',\n                'db'=\u003e 'databaseName',\n                'port' =\u003e 3306,\n                'prefix' =\u003e 'my_',\n                'charset' =\u003e 'utf8')\n);\n```\nTo select database use connection() method\n```php\n$users = $db-\u003econnection('slave')-\u003eget('users');\n```\n\n### Objects mapping\ndbObject.php is an object mapping library built on top of mysqliDb to provide model representation functionality.\nSee \u003ca href='dbObject.md'\u003edbObject manual for more information\u003c/a\u003e\n\n### Insert Query\nSimple example\n```php\n$data = Array (\"login\" =\u003e \"admin\",\n               \"firstName\" =\u003e \"John\",\n               \"lastName\" =\u003e 'Doe'\n);\n$id = $db-\u003einsert ('users', $data);\nif($id)\n    echo 'user was created. Id=' . $id;\n```\n\nInsert with functions use\n```php\n$data = Array (\n\t'login' =\u003e 'admin',\n    'active' =\u003e true,\n\t'firstName' =\u003e 'John',\n\t'lastName' =\u003e 'Doe',\n\t'password' =\u003e $db-\u003efunc('SHA1(?)',Array (\"secretpassword+salt\")),\n\t// password = SHA1('secretpassword+salt')\n\t'createdAt' =\u003e $db-\u003enow(),\n\t// createdAt = NOW()\n\t'expires' =\u003e $db-\u003enow('+1Y')\n\t// expires = NOW() + interval 1 year\n\t// Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear\n);\n\n$id = $db-\u003einsert ('users', $data);\nif ($id)\n    echo 'user was created. Id=' . $id;\nelse\n    echo 'insert failed: ' . $db-\u003egetLastError();\n```\n\nInsert with on duplicate key update\n```php\n$data = Array (\"login\" =\u003e \"admin\",\n               \"firstName\" =\u003e \"John\",\n               \"lastName\" =\u003e 'Doe',\n               \"createdAt\" =\u003e $db-\u003enow(),\n               \"updatedAt\" =\u003e $db-\u003enow(),\n);\n$updateColumns = Array (\"updatedAt\");\n$lastInsertId = \"id\";\n$db-\u003eonDuplicate($updateColumns, $lastInsertId);\n$id = $db-\u003einsert ('users', $data);\n```\n\nInsert multiple datasets at once\n```php\n$data = Array(\n    Array (\"login\" =\u003e \"admin\",\n        \"firstName\" =\u003e \"John\",\n        \"lastName\" =\u003e 'Doe'\n    ),\n    Array (\"login\" =\u003e \"other\",\n        \"firstName\" =\u003e \"Another\",\n        \"lastName\" =\u003e 'User',\n        \"password\" =\u003e \"very_cool_hash\"\n    )\n);\n$ids = $db-\u003einsertMulti('users', $data);\nif(!$ids) {\n    echo 'insert failed: ' . $db-\u003egetLastError();\n} else {\n    echo 'new users inserted with following id\\'s: ' . implode(', ', $ids);\n}\n```\n\nIf all datasets only have the same keys, it can be simplified\n```php\n$data = Array(\n    Array (\"admin\", \"John\", \"Doe\"),\n    Array (\"other\", \"Another\", \"User\")\n);\n$keys = Array(\"login\", \"firstName\", \"lastName\");\n\n$ids = $db-\u003einsertMulti('users', $data, $keys);\nif(!$ids) {\n    echo 'insert failed: ' . $db-\u003egetLastError();\n} else {\n    echo 'new users inserted with following id\\'s: ' . implode(', ', $ids);\n}\n```\n\n### Replace Query\n\u003ca href='https://dev.mysql.com/doc/refman/5.0/en/replace.html'\u003eReplace()\u003c/a\u003e method implements same API as insert();\n\n### Update Query\n```php\n$data = Array (\n\t'firstName' =\u003e 'Bobby',\n\t'lastName' =\u003e 'Tables',\n\t'editCount' =\u003e $db-\u003einc(2),\n\t// editCount = editCount + 2;\n\t'active' =\u003e $db-\u003enot()\n\t// active = !active;\n);\n$db-\u003ewhere ('id', 1);\nif ($db-\u003eupdate ('users', $data))\n    echo $db-\u003ecount . ' records were updated';\nelse\n    echo 'update failed: ' . $db-\u003egetLastError();\n```\n\n`update()` also support limit parameter:\n```php\n$db-\u003eupdate ('users', $data, 10);\n// Gives: UPDATE users SET ... LIMIT 10\n```\n\n### Select Query\nAfter any select/get function calls amount or returned rows is stored in $count variable\n```php\n$users = $db-\u003eget('users'); //contains an Array of all users \n$users = $db-\u003eget('users', 10); //contains an Array 10 users\n```\n\nor select with custom columns set. Functions also could be used\n\n```php\n$cols = Array (\"id\", \"name\", \"email\");\n$users = $db-\u003eget (\"users\", null, $cols);\nif ($db-\u003ecount \u003e 0)\n    foreach ($users as $user) { \n        print_r ($user);\n    }\n```\n\nor select just one row\n\n```php\n$db-\u003ewhere (\"id\", 1);\n$user = $db-\u003egetOne (\"users\");\necho $user['id'];\n\n$stats = $db-\u003egetOne (\"users\", \"sum(id), count(*) as cnt\");\necho \"total \".$stats['cnt']. \"users found\";\n```\n\nor select one column value or function result\n\n```php\n$count = $db-\u003egetValue (\"users\", \"count(*)\");\necho \"{$count} users found\";\n```\n\nselect one column value or function result from multiple rows:\n```php\n$logins = $db-\u003egetValue (\"users\", \"login\", null);\n// select login from users\n$logins = $db-\u003egetValue (\"users\", \"login\", 5);\n// select login from users limit 5\nforeach ($logins as $login)\n    echo $login;\n```\n\n### Insert Data\nYou can also load .CSV or .XML data into a specific table.\nTo insert .csv data, use the following syntax:\n```php\n$path_to_file = \"/home/john/file.csv\";\n$db-\u003eloadData(\"users\", $path_to_file);\n```\nThis will load a .csv file called **file.csv** in the folder **/home/john/** (john's home directory.)\nYou can also attach an optional array of options.\nValid options are:\n\n```php\nArray(\n\t\"fieldChar\" =\u003e ';', \t// Char which separates the data\n\t\"lineChar\" =\u003e '\\r\\n', \t// Char which separates the lines\n\t\"linesToIgnore\" =\u003e 1\t// Amount of lines to ignore at the beginning of the import\n);\n```\n\nAttach them using\n```php\n$options = Array(\"fieldChar\" =\u003e ';', \"lineChar\" =\u003e '\\r\\n', \"linesToIgnore\" =\u003e 1);\n$db-\u003eloadData(\"users\", \"/home/john/file.csv\", $options);\n// LOAD DATA ...\n```\n\nYou can specify to **use LOCAL DATA** instead of **DATA**:\n```php\n$options = Array(\"fieldChar\" =\u003e ';', \"lineChar\" =\u003e '\\r\\n', \"linesToIgnore\" =\u003e 1, \"loadDataLocal\" =\u003e true);\n$db-\u003eloadData(\"users\", \"/home/john/file.csv\", $options);\n// LOAD DATA LOCAL ...\n```\n\n### Insert XML\nTo load XML data into a table, you can use the method **loadXML**.\nThe syntax is smillar to the loadData syntax.\n```php\n$path_to_file = \"/home/john/file.xml\";\n$db-\u003eloadXML(\"users\", $path_to_file);\n```\n\nYou can also add optional parameters.\nValid parameters:\n```php\nArray(\n\t\"linesToIgnore\" =\u003e 0,\t\t// Amount of lines / rows to ignore at the beginning of the import\n\t\"rowTag\"\t=\u003e \"\u003cuser\u003e\"\t// The tag which marks the beginning of an entry\n)\n```\n\nUsage:\n```php\n$options = Array(\"linesToIgnore\" =\u003e 0, \"rowTag\"\t=\u003e \"\u003cuser\u003e\"):\n$path_to_file = \"/home/john/file.xml\";\n$db-\u003eloadXML(\"users\", $path_to_file, $options);\n```\n\n### Pagination\nUse paginate() instead of get() to fetch paginated result\n```php\n$page = 1;\n// set page limit to 2 results per page. 20 by default\n$db-\u003epageLimit = 2;\n$products = $db-\u003earraybuilder()-\u003epaginate(\"products\", $page);\necho \"showing $page out of \" . $db-\u003etotalPages;\n\n```\n\n### Result transformation / map\nInstead of getting an pure array of results its possible to get result in an associative array with a needed key. If only 2 fields to fetch will be set in get(),\nmethod will return result in array($k =\u003e $v) and array ($k =\u003e array ($v, $v)) in rest of the cases.\n\n```php\n$user = $db-\u003emap ('login')-\u003eObjectBuilder()-\u003egetOne ('users', 'login, id');\nArray\n(\n    [user1] =\u003e 1\n)\n\n$user = $db-\u003emap ('login')-\u003eObjectBuilder()-\u003egetOne ('users', 'id,login,createdAt');\nArray\n(\n    [user1] =\u003e stdClass Object\n        (\n            [id] =\u003e 1\n            [login] =\u003e user1\n            [createdAt] =\u003e 2015-10-22 22:27:53\n        )\n\n)\n```\n\n### Defining a return type\nMysqliDb can return result in 3 different formats: Array of Array, Array of Objects and a Json string. To select a return type use ArrayBuilder(), ObjectBuilder() and JsonBuilder() methods. Note that ArrayBuilder() is a default return type\n```php\n// Array return type\n$u= $db-\u003egetOne(\"users\");\necho $u['login'];\n// Object return type\n$u = $db-\u003eObjectBuilder()-\u003egetOne(\"users\");\necho $u-\u003elogin;\n// Json return type\n$json = $db-\u003eJsonBuilder()-\u003egetOne(\"users\");\n```\n\n### Running raw SQL queries\n```php\n$users = $db-\u003erawQuery('SELECT * from users where id \u003e= ?', Array (10));\nforeach ($users as $user) {\n    print_r ($user);\n}\n```\nTo avoid long if checks there are couple helper functions to work with raw query select results:\n\nGet 1 row of results:\n```php\n$user = $db-\u003erawQueryOne('SELECT * from users where id=?', Array(10));\necho $user['login'];\n// Object return type\n$user = $db-\u003eObjectBuilder()-\u003erawQueryOne('SELECT * from users where id=?', Array(10));\necho $user-\u003elogin;\n```\nGet 1 column value as a string:\n```php\n$password = $db-\u003erawQueryValue('SELECT password from users where id=? limit 1', Array(10));\necho \"Password is {$password}\";\nNOTE: for a rawQueryValue() to return string instead of an array 'limit 1' should be added to the end of the query.\n```\nGet 1 column value from multiple rows:\n```php\n$logins = $db-\u003erawQueryValue('SELECT login from users limit 10');\nforeach ($logins as $login)\n    echo $login;\n```\n\nMore advanced examples:\n```php\n$params = Array(1, 'admin');\n$users = $db-\u003erawQuery(\"SELECT id, firstName, lastName FROM users WHERE id = ? AND login = ?\", $params);\nprint_r($users); // contains Array of returned rows\n\n// will handle any SQL query\n$params = Array(10, 1, 10, 11, 2, 10);\n$q = \"(\n    SELECT a FROM t1\n        WHERE a = ? AND B = ?\n        ORDER BY a LIMIT ?\n) UNION (\n    SELECT a FROM t2 \n        WHERE a = ? AND B = ?\n        ORDER BY a LIMIT ?\n)\";\n$results = $db-\u003erawQuery ($q, $params);\nprint_r ($results); // contains Array of returned rows\n```\n\n### Where / Having Methods\n`where()`, `orWhere()`, `having()` and `orHaving()` methods allows you to specify where and having conditions of the query. All conditions supported by where() are supported by having() as well.\n\nWARNING: In order to use column to column comparisons only raw where conditions should be used as column name or functions cannot be passed as a bind variable.\n\nRegular == operator with variables:\n```php\n$db-\u003ewhere ('id', 1);\n$db-\u003ewhere ('login', 'admin');\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users WHERE id=1 AND login='admin';\n\n// Or you can also use Chain Loaders for above query\n$results = $db-\u003ewhere ('id', 1)\n                -\u003ewhere ('login', 'admin')\n                -\u003eget('users');\n```\n\n```php\n$db-\u003ewhere ('id', 1);\n$db-\u003ehaving ('login', 'admin');\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users WHERE id=1 HAVING login='admin';\n```\n\n\nRegular == operator with column to column comparison:\n```php\n// WRONG\n$db-\u003ewhere ('lastLogin', 'createdAt');\n// CORRECT\n$db-\u003ewhere ('lastLogin = createdAt');\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users WHERE lastLogin = createdAt;\n```\n\n```php\n$db-\u003ewhere ('id', 50, \"\u003e=\");\n// or $db-\u003ewhere ('id', Array ('\u003e=' =\u003e 50));\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users WHERE id \u003e= 50;\n```\n\nBETWEEN / NOT BETWEEN:\n```php\n$db-\u003ewhere('id', Array (4, 20), 'BETWEEN');\n// or $db-\u003ewhere ('id', Array ('BETWEEN' =\u003e Array(4, 20)));\n\n$results = $db-\u003eget('users');\n// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20\n```\n\nIN / NOT IN:\n```php\n$db-\u003ewhere('id', Array(1, 5, 27, -1, 'd'), 'IN');\n// or $db-\u003ewhere('id', Array( 'IN' =\u003e Array(1, 5, 27, -1, 'd') ) );\n\n$results = $db-\u003eget('users');\n// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');\n```\n\nOR CASE:\n```php\n$db-\u003ewhere ('firstName', 'John');\n$db-\u003eorWhere ('firstName', 'Peter');\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter'\n```\n\nNULL comparison:\n```php\n$db-\u003ewhere (\"lastName\", NULL, 'IS NOT');\n$results = $db-\u003eget(\"users\");\n// Gives: SELECT * FROM users where lastName IS NOT NULL\n```\n\nLIKE comparison:\n```php\n$db-\u003ewhere (\"fullName\", 'John%', 'like');\n$results = $db-\u003eget(\"users\");\n// Gives: SELECT * FROM users where fullName like 'John%'\n```\n\nAlso you can use raw where conditions:\n```php\n$db-\u003ewhere (\"id != companyId\");\n$db-\u003ewhere (\"DATE(createdAt) = DATE(lastLogin)\");\n$results = $db-\u003eget(\"users\");\n```\n\nOr raw condition with variables:\n```php\n$db-\u003ewhere (\"(id = ? or id = ?)\", Array(6,2));\n$db-\u003ewhere (\"login\",\"mike\");\n$res = $db-\u003eget (\"users\");\n// Gives: SELECT * FROM users WHERE (id = 6 or id = 2) and login='mike';\n```\n\n\nFind the total number of rows matched. Simple pagination example:\n```php\n$offset = 10;\n$count = 15;\n$users = $db-\u003ewithTotalCount()-\u003eget('users', Array ($offset, $count));\necho \"Showing {$count} from {$db-\u003etotalCount}\";\n```\n\n### Query Keywords\nTo add LOW PRIORITY | DELAYED | HIGH PRIORITY | IGNORE and the rest of the mysql keywords to INSERT (), REPLACE (), GET (), UPDATE (), DELETE() method or FOR UPDATE | LOCK IN SHARE MODE into SELECT ():\n```php\n$db-\u003esetQueryOption ('LOW_PRIORITY')-\u003einsert ($table, $param);\n// GIVES: INSERT LOW_PRIORITY INTO table ...\n```\n```php\n$db-\u003esetQueryOption ('FOR UPDATE')-\u003eget ('users');\n// GIVES: SELECT * FROM USERS FOR UPDATE;\n```\n\nAlso you can use an array of keywords:\n```php\n$db-\u003esetQueryOption (Array('LOW_PRIORITY', 'IGNORE'))-\u003einsert ($table,$param);\n// GIVES: INSERT LOW_PRIORITY IGNORE INTO table ...\n```\n\nSame way keywords could be used in SELECT queries as well:\n```php\n$db-\u003esetQueryOption ('SQL_NO_CACHE');\n$db-\u003eget(\"users\");\n// GIVES: SELECT SQL_NO_CACHE * FROM USERS;\n```\n\nOptionally you can use method chaining to call where multiple times without referencing your object over and over:\n\n```php\n$results = $db\n\t-\u003ewhere('id', 1)\n\t-\u003ewhere('login', 'admin')\n\t-\u003eget('users');\n```\n\n### Delete Query\n```php\n$db-\u003ewhere('id', 1);\nif($db-\u003edelete('users')) echo 'successfully deleted';\n```\n\n\n### Ordering method\n```php\n$db-\u003eorderBy(\"id\",\"asc\");\n$db-\u003eorderBy(\"login\",\"Desc\");\n$db-\u003eorderBy(\"RAND ()\");\n$results = $db-\u003eget('users');\n// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();\n```\n\nOrder by values example:\n```php\n$db-\u003eorderBy('userGroup', 'ASC', array('superuser', 'admin', 'users'));\n$db-\u003eget('users');\n// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;\n```\n\nIf you are using setPrefix () functionality and need to use table names in orderBy() method make sure that table names are escaped with ``.\n\n```php\n$db-\u003esetPrefix (\"t_\");\n$db-\u003eorderBy (\"users.id\",\"asc\");\n$results = $db-\u003eget ('users');\n// WRONG: That will give: SELECT * FROM t_users ORDER BY users.id ASC;\n\n$db-\u003esetPrefix (\"t_\");\n$db-\u003eorderBy (\"`users`.id\", \"asc\");\n$results = $db-\u003eget ('users');\n// CORRECT: That will give: SELECT * FROM t_users ORDER BY t_users.id ASC;\n```\n\n### Grouping method\n```php\n$db-\u003egroupBy (\"name\");\n$results = $db-\u003eget ('users');\n// Gives: SELECT * FROM users GROUP BY name;\n```\n\n### JOIN method\nJoin table products with table users with LEFT JOIN by tenantID\n```php\n$db-\u003ejoin(\"users u\", \"p.tenantID=u.tenantID\", \"LEFT\");\n$db-\u003ewhere(\"u.id\", 6);\n$products = $db-\u003eget (\"products p\", null, \"u.name, p.productName\");\nprint_r ($products);\n// Gives: SELECT u.name, p.productName FROM products p LEFT JOIN users u ON p.tenantID=u.tenantID WHERE u.id = 6\n```\n\n### Join Conditions\nAdd AND condition to join statement\n```php\n$db-\u003ejoin(\"users u\", \"p.tenantID=u.tenantID\", \"LEFT\");\n$db-\u003ejoinWhere(\"users u\", \"u.tenantID\", 5);\n$products = $db-\u003eget (\"products p\", null, \"u.name, p.productName\");\nprint_r ($products);\n// Gives: SELECT  u.name, p.productName FROM products p LEFT JOIN users u ON (p.tenantID=u.tenantID AND u.tenantID = 5)\n```\nAdd OR condition to join statement\n```php\n$db-\u003ejoin(\"users u\", \"p.tenantID=u.tenantID\", \"LEFT\");\n$db-\u003ejoinOrWhere(\"users u\", \"u.tenantID\", 5);\n$products = $db-\u003eget (\"products p\", null, \"u.name, p.productName\");\nprint_r ($products);\n// Gives: SELECT  u.login, p.productName FROM products p LEFT JOIN users u ON (p.tenantID=u.tenantID OR u.tenantID = 5)\n```\n\n### Properties sharing\nIt is also possible to copy properties\n\n```php\n$db-\u003ewhere (\"agentId\", 10);\n$db-\u003ewhere (\"active\", true);\n\n$customers = $db-\u003ecopy ();\n$res = $customers-\u003eget (\"customers\", Array (10, 10));\n// SELECT * FROM customers WHERE agentId = 10 AND active = 1 LIMIT 10, 10\n\n$cnt = $db-\u003egetValue (\"customers\", \"count(id)\");\necho \"total records found: \" . $cnt;\n// SELECT count(id) FROM customers WHERE agentId = 10 AND active = 1\n```\n\n### Subqueries\nSubquery init\n\nSubquery init without an alias to use in inserts/updates/where Eg. (select * from users)\n```php\n$sq = $db-\u003esubQuery();\n$sq-\u003eget (\"users\");\n```\n \nA subquery with an alias specified to use in JOINs . Eg. (select * from users) sq\n```php\n$sq = $db-\u003esubQuery(\"sq\");\n$sq-\u003eget (\"users\");\n```\n\nSubquery in selects:\n```php\n$ids = $db-\u003esubQuery ();\n$ids-\u003ewhere (\"qty\", 2, \"\u003e\");\n$ids-\u003eget (\"products\", null, \"userId\");\n\n$db-\u003ewhere (\"id\", $ids, 'in');\n$res = $db-\u003eget (\"users\");\n// Gives SELECT * FROM users WHERE id IN (SELECT userId FROM products WHERE qty \u003e 2)\n```\n\nSubquery in inserts:\n```php\n$userIdQ = $db-\u003esubQuery ();\n$userIdQ-\u003ewhere (\"id\", 6);\n$userIdQ-\u003egetOne (\"users\", \"name\"),\n\n$data = Array (\n    \"productName\" =\u003e \"test product\",\n    \"userId\" =\u003e $userIdQ,\n    \"lastUpdated\" =\u003e $db-\u003enow()\n);\n$id = $db-\u003einsert (\"products\", $data);\n// Gives INSERT INTO PRODUCTS (productName, userId, lastUpdated) values (\"test product\", (SELECT name FROM users WHERE id = 6), NOW());\n```\n\nSubquery in joins:\n```php\n$usersQ = $db-\u003esubQuery (\"u\");\n$usersQ-\u003ewhere (\"active\", 1);\n$usersQ-\u003eget (\"users\");\n\n$db-\u003ejoin($usersQ, \"p.userId=u.id\", \"LEFT\");\n$products = $db-\u003eget (\"products p\", null, \"u.login, p.productName\");\nprint_r ($products);\n// SELECT u.login, p.productName FROM products p LEFT JOIN (SELECT * FROM t_users WHERE active = 1) u on p.userId=u.id;\n```\n\n### EXISTS / NOT EXISTS condition\n```php\n$sub = $db-\u003esubQuery();\n$sub-\u003ewhere(\"company\", 'testCompany');\n$sub-\u003eget (\"users\", null, 'userId');\n$db-\u003ewhere (null, $sub, 'exists');\n$products = $db-\u003eget (\"products\");\n// Gives SELECT * FROM products WHERE EXISTS (SELECT userId FROM users WHERE company='testCompany')\n```\n\n### Has method\nA convenient function that returns TRUE if exists at least an element that satisfy the where condition specified calling the \"where\" method before this one.\n```php\n$db-\u003ewhere(\"user\", $user);\n$db-\u003ewhere(\"password\", md5($password));\nif($db-\u003ehas(\"users\")) {\n    return \"You are logged\";\n} else {\n    return \"Wrong user/password\";\n}\n``` \n### Helper methods\nDisconnect from the database:\n```php\n    $db-\u003edisconnect();\n```\n\nReconnect in case mysql connection died:\n```php\nif (!$db-\u003eping())\n    $db-\u003econnect()\n```\n\nGet last executed SQL query:\nPlease note that this method returns the SQL query only for debugging purposes as its execution most likely will fail due to missing quotes around char variables.\n```php\n    $db-\u003eget('users');\n    echo \"Last executed query was \". $db-\u003egetLastQuery();\n```\n\nCheck if table exists:\n```php\n    if ($db-\u003etableExists ('users'))\n        echo \"hooray\";\n```\n\nmysqli_real_escape_string() wrapper:\n```php\n    $escaped = $db-\u003eescape (\"' and 1=1\");\n```\n\n### Transaction helpers\nPlease keep in mind that transactions are working on innoDB tables.\nRollback transaction if insert fails:\n```php\n$db-\u003estartTransaction();\n...\nif (!$db-\u003einsert ('myTable', $insertData)) {\n    //Error while saving, cancel new record\n    $db-\u003erollback();\n} else {\n    //OK\n    $db-\u003ecommit();\n}\n```\n\n\n### Error helpers\nAfter you executed a query you have options to check if there was an error. You can get the MySQL error string or the error code for the last executed query. \n```php\n$db-\u003ewhere('login', 'admin')-\u003eupdate('users', ['firstName' =\u003e 'Jack']);\n\nif ($db-\u003egetLastErrno() === 0)\n    echo 'Update succesfull';\nelse\n    echo 'Update failed. Error: '. $db-\u003egetLastError();\n```\n\n### Query execution time benchmarking\nTo track query execution time setTrace() function should be called.\n```php\n$db-\u003esetTrace (true);\n// As a second parameter it is possible to define prefix of the path which should be striped from filename\n// $db-\u003esetTrace (true, $_SERVER['SERVER_ROOT']);\n$db-\u003eget(\"users\");\n$db-\u003eget(\"test\");\nprint_r ($db-\u003etrace);\n```\n\n```\n    [0] =\u003e Array\n        (\n            [0] =\u003e SELECT  * FROM t_users ORDER BY `id` ASC\n            [1] =\u003e 0.0010669231414795\n            [2] =\u003e MysqliDb-\u003eget() \u003e\u003e  file \"/avb/work/PHP-MySQLi-Database-Class/tests.php\" line #151\n        )\n\n    [1] =\u003e Array\n        (\n            [0] =\u003e SELECT  * FROM t_test\n            [1] =\u003e 0.00069189071655273\n            [2] =\u003e MysqliDb-\u003eget() \u003e\u003e  file \"/avb/work/PHP-MySQLi-Database-Class/tests.php\" line #152\n        )\n\n```\n\n### Table Locking\nTo lock tables, you can use the **lock** method together with **setLockMethod**. \nThe following example will lock the table **users** for **write** access.\n```php\n$db-\u003esetLockMethod(\"WRITE\")-\u003elock(\"users\");\n```\n\nCalling another **-\u003elock()** will remove the first lock.\nYou can also use\n```php\n$db-\u003eunlock();\n```\nto unlock the previous locked tables.\nTo lock multiple tables, you can use an array.\nExample:\n```php\n$db-\u003esetLockMethod(\"READ\")-\u003elock(array(\"users\", \"log\"));\n```\nThis will lock the tables **users** and **log** for **READ** access only.\nMake sure you use **unlock()* afterwards or your tables will remain locked!\n\n","funding_links":["https://www.paypal.com/cgi-bin/webscr?cmd=_donations\u0026business=a%2ebutenka%40gmail%2ecom\u0026lc=DO\u0026item_name=mysqlidb\u0026currency_code=USD\u0026bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FThingEngineer%2FPHP-MySQLi-Database-Class","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FThingEngineer%2FPHP-MySQLi-Database-Class","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FThingEngineer%2FPHP-MySQLi-Database-Class/lists"}