### Install MysqliDb with Composer Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Instructions for installing the MysqliDb library using Composer, a dependency manager for PHP. This method ensures the library is managed and updated automatically. ```bash composer require thingengineer/mysqli-database-class:dev-master ``` -------------------------------- ### PHP: Delete Query Example Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Provides a simple example of how to perform a DELETE operation on a table using the `delete()` method, often in conjunction with a `where()` clause to specify which rows to remove. ```php $db->where('id', 1); if($db->delete('users')) echo 'successfully deleted'; ``` -------------------------------- ### Initialize MysqliDb with Existing mysqli Object Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Provides an example of initializing MysqliDb using an already established mysqli connection object. This is useful for integrating with existing database connections. ```php $mysqli = new mysqli ('host', 'username', 'password', 'databaseName'); $db = new MysqliDb ($mysqli); ``` -------------------------------- ### Get MysqliDb Instance Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Explains how to retrieve a singleton instance of MysqliDb. This is useful for accessing the same database connection object across different parts of an application. ```php function init () { // db staying private here $db = new MysqliDb ('host', 'username', 'password', 'databaseName'); } ... function myfunc () { // obtain db object created in init () $db = MysqliDb::getInstance(); ... ``` -------------------------------- ### PHP: Pagination with Total Count Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to retrieve a paginated subset of data and simultaneously get the total count of matching rows using the `withTotalCount()` method. This is useful for implementing pagination controls. ```php $offset = 10; $count = 15; $users = $db->withTotalCount()->get('users', Array ($offset, $count)); echo "Showing {$count} from {$db->totalCount}"; ``` -------------------------------- ### PHP Selecting Records with Where Condition and Limit Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Illustrates how to retrieve records based on a WHERE condition and apply a limit to the result set, using the `where()` and `get()` methods. ```php $users = user::where("login", "demo")->get(Array (10, 20)); foreach ($users as $u) ... ``` -------------------------------- ### Managing Transactions with PHP-MySQLi Database Class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Details transaction management, including starting a transaction (`startTransaction()`), committing changes (`commit()`), and rolling back in case of errors (`rollback()`). Transactions ensure data integrity by grouping multiple SQL operations into a single atomic unit, working with InnoDB tables. ```php $db->startTransaction(); ... if (!$db->insert ('myTable', $insertData)) { //Error while saving, cancel new record $db->rollback(); } else { //OK $db->commit(); } ``` -------------------------------- ### PHP JOIN Operations with MySQLi Database Class Source: https://context7.com/thingengineer/php-mysqli-database-class/llms.txt Explains how to perform JOIN operations to combine data from multiple tables using the PHP MySQLi Database Class. Includes examples for LEFT JOIN, INNER JOIN with multiple tables, JOIN with subqueries, and JOINs with additional conditions. ```php join('profiles p', 'p.user_id = u.id', 'LEFT'); $db->where('u.status', 'active'); $results = $db->get('users u', null, 'u.*, p.bio, p.avatar'); // INNER JOIN with multiple tables $db->join('orders o', 'o.user_id = u.id', 'INNER'); $db->join('products p', 'p.id = o.product_id', 'INNER'); $db->where('o.status', 'completed'); $results = $db->get('users u', null, 'u.username, p.name as product, o.total'); // JOIN with subquery $sub = $db->subQuery('sq'); $sub->where('status', 'active'); $sub->get('products', null, 'category_id, COUNT(*) as cnt'); $db->join($sub, 'sq.category_id = c.id', 'LEFT'); $categories = $db->get('categories c', null, 'c.name, sq.cnt'); // JOIN with additional conditions $db->join('user_roles ur', 'ur.user_id = u.id', 'INNER'); $db->joinWhere('user_roles ur', 'ur.role', 'admin'); $db->joinWhere('user_roles ur', 'ur.expires_at >', $db->now()); $admins = $db->get('users u'); ?> ``` -------------------------------- ### Paginate Results in PHP Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Illustrates how to implement pagination for query results. Use the `paginate()` method instead of `get()`. The static property `product::$pageLimit` can be set to control the number of results per page. ```php $page = 1; // set page limit to 2 results per page. 20 by default product::$pageLimit = 2; $products = product::arraybuilder()->paginate($page); echo "showing $page out of " . product::$totalPages; ``` -------------------------------- ### Paginate Results with php-mysqli-database-class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Explains how to fetch paginated results from a table using the paginate() method instead of get(). It allows setting a custom page limit for the number of results per page. The total number of pages is accessible via the totalPages property. ```php $page = 1; // set page limit to 2 results per page. 20 by default $db->pageLimit = 2; $products = $db->arraybuilder()->paginate("products", $page); echo "showing $page out of " . $db->totalPages; ``` -------------------------------- ### Using Subqueries in INSERT with PHP-MySQLi Database Class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Illustrates how to use a subquery to fetch a value for an INSERT statement. In this example, a subquery retrieves the `name` of a user (based on `id = 6`) to be used as the `userId` for a new product insertion. This allows dynamic data population. ```php $userIdQ = $db->subQuery (); $userIdQ->where ("id", 6); $userIdQ->getOne ("users", "name"), $data = Array ( "productName" => "test product", "userId" => $userIdQ, "lastUpdated" => $db->now() ); $id = $db->insert ("products", $data); // Gives INSERT INTO PRODUCTS (productName, userId, lastUpdated) values ("test product", (SELECT name FROM users WHERE id = 6), NOW()); ``` -------------------------------- ### PHP MySQLi Helper Methods and Utilities Source: https://context7.com/thingengineer/php-mysqli-database-class/llms.txt Provides utility functions for data manipulation and query building in PHP using the MySQLi Database Class. Includes methods for checking existence, getting last insert ID, escaping strings, retrieving last query/error, date interval manipulation, increment/decrement, custom functions, pinging the connection, counting results, and mapping results by key. ```php where('email', 'test@example.com'); if ($db->has('users')) { echo "Email already registered"; } // Get last insert ID $userId = $db->insert('users', $userData); $lastId = $db->getInsertId(); // Escape string $safe = $db->escape($_POST['username']); // Get last executed query $db->where('status', 'active'); $users = $db->get('users'); echo $db->getLastQuery(); // Get last error if (!$db->insert('users', $data)) { echo $db->getLastError(); echo "Error code: " . $db->getLastErrno(); } // Date interval helper $lastWeek = $db->interval('-7d'); $db->where('created_at >', $lastWeek); $recentUsers = $db->get('users'); // Increment/decrement helpers $data = [ 'view_count' => $db->inc(1), 'credits' => $db->dec(10), 'is_featured' => $db->not() ]; // Custom function in query $data = [ 'full_address' => $db->func('CONCAT(?, ", ", ?, ", ", ?)', [$street, $city, $zip]) ]; // Ping connection (keep-alive) if (!$db->ping()) { echo "Connection lost"; } // Result count $users = $db->get('users'); echo "Found {$db->count} records"; // Map results by key $users = $db->map('username')->get('users', null, 'username, email'); // Returns: ['john' => 'john@example.com', 'jane' => 'jane@example.com'] ``` -------------------------------- ### Return Data as Array in PHP Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Shows how to retrieve database results as an associative array instead of an object. The `ArrayBuilder()` function should be called before other methods like `byId()` or `get()`. Use `with()` to include related data. ```php $user = user::ArrayBuilder()->byId(1); echo $user['login']; $users = user::ArrayBuilder()->orderBy("id", "desc")->get(); foreach ($users as $u) echo $u['login']; ``` ```php $user = user::ArrayBuilder()->with("product")->byId(1); print_r ($user['products']); ``` -------------------------------- ### PHP MySQLi Database Initialization and Connection Source: https://context7.com/thingengineer/php-mysqli-database-class/llms.txt Demonstrates how to initialize the MysqliDb class for database connections. Supports simple and advanced configurations, including multiple database connections and singleton access. Ensure the MysqliDb.php file is included. ```php 'localhost', 'username' => 'dbuser', 'password' => 'pass123', 'db' => 'ecommerce', 'port' => 3306, 'prefix' => 'shop_', 'charset' => 'utf8mb4' ]); // Multiple database connections $db->addConnection('analytics', [ 'host' => 'analytics.example.com', 'username' => 'analyst', 'password' => 'analytics_pass', 'db' => 'stats', 'charset' => 'utf8mb4' ]); // Use specific connection $visitors = $db->connection('analytics')->get('visitor_logs', 100); // Singleton pattern access MysqliDb::getInstance(); ?> ``` -------------------------------- ### Initialize MysqliDb with Advanced Options Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Illustrates advanced initialization of MysqliDb, allowing configuration of host, username, password, database name, port, table prefix, and charset. Optional parameters can be set to null. ```php $db = new MysqliDb (Array ( 'host' => 'host', 'username' => 'username', 'password' => 'password', 'db'=> 'databaseName', 'port' => 3306, 'prefix' => 'my_', 'charset' => 'utf8')); ``` -------------------------------- ### PHP Initialization and Autoloading Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Includes the necessary MysqliDb and dbObject classes. Demonstrates how to instantiate the database connection and enable autoloading for model classes from a specified directory. ```php require_once("libs/MysqliDb.php"); require_once("libs/dbObject.php"); // db instance $db = new Mysqlidb('localhost', 'user', '', 'testdb'); // enable class autoloading dbObject::autoload("models"); ``` -------------------------------- ### Return Data as JSON in PHP Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Demonstrates how to get query results directly in JSON format. This is achieved by using `JsonBuilder()` in conjunction with other query methods like `with()` and `byId()`. ```php $userjson = user::JsonBuilder()->with("product")->byId(1); ``` -------------------------------- ### Initialize MysqliDb with Basic Connection Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Shows the basic initialization of the MysqliDb class with host, username, password, and database name. UTF8 charset is set by default. ```php $db = new MysqliDb ('host', 'username', 'password', 'databaseName'); ``` -------------------------------- ### Database Initialization and Connection Source: https://context7.com/thingengineer/php-mysqli-database-class/llms.txt Initialize database connection with automatic UTF-8 charset and prepared statement support. Supports simple and advanced initialization, multiple connections, and singleton access. ```APIDOC ## Database Initialization and Connection ### Description Initialize database connection with automatic UTF-8 charset and prepared statement support. ### Method `new MysqliDb(host, username, password, db, port, prefix, charset)` or `new MysqliDb(options_array)` ### Endpoint N/A (Class constructor) ### Parameters #### Constructor Parameters (Simple) - **host** (string) - Required - The database host. - **username** (string) - Required - The database username. - **password** (string) - Required - The database password. - **db** (string) - Required - The database name. - **port** (integer) - Optional - The database port (default: 3306). - **prefix** (string) - Optional - Table prefix (default: ''). - **charset** (string) - Optional - Character set (default: 'utf8mb4'). #### Constructor Parameters (Advanced - Array) - **options_array** (array) - Required - An associative array of connection options. - **host** (string) - Required - The database host. - **username** (string) - Required - The database username. - **password** (string) - Required - The database password. - **db** (string) - Required - The database name. - **port** (integer) - Optional - The database port (default: 3306). - **prefix** (string) - Optional - Table prefix (default: ''). - **charset** (string) - Optional - Character set (default: 'utf8mb4'). ### Methods - **`addConnection(connection_name, options_array)`**: Adds a named database connection. - **`connection(connection_name)`**: Switches to a specific database connection. - **`getInstance()`**: Returns the singleton instance of the database class. ### Request Example (Simple Initialization) ```php ``` ### Request Example (Advanced Initialization) ```php 'localhost', 'username' => 'dbuser', 'password' => 'pass123', 'db' => 'ecommerce', 'port' => 3306, 'prefix' => 'shop_', 'charset' => 'utf8mb4' ]); ?> ``` ### Request Example (Multiple Connections) ```php addConnection('analytics', [ 'host' => 'analytics.example.com', 'username' => 'analyst', 'password' => 'analytics_pass', 'db' => 'stats', 'charset' => 'utf8mb4' ]); $visitors = $db->connection('analytics')->get('visitor_logs', 100); ?> ``` ### Request Example (Singleton) ```php ``` ``` -------------------------------- ### Select Database Connection Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Shows how to switch between different database connections using the `connection()` method. This allows querying different databases within the same script. ```php $users = $db->connection('slave')->get('users'); ``` -------------------------------- ### Performing LEFT JOIN with PHP-MySQLi Database Class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Shows how to perform a LEFT JOIN between two tables (`products` and `users`) based on a common `tenantID`. It also includes applying a WHERE clause and selecting specific columns. The method requires table names, join conditions, and join type. ```php $db->join("users u", "p.tenantID=u.tenantID", "LEFT"); $db->where("u.id", 6); $products = $db->get ("products p", null, "u.name, p.productName"); print_r ($products); // Gives: SELECT u.name, p.productName FROM products p LEFT JOIN users u ON p.tenantID=u.tenantID WHERE u.id = 6 ``` -------------------------------- ### Using EXISTS Condition with Subquery in PHP-MySQLi Database Class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to use the EXISTS operator with a subquery. The example checks if there exists any `userId` in the `users` table for a specific company. This is an efficient way to check for the existence of related records without retrieving them. ```php $sub = $db->subQuery(); $sub->where("company", 'testCompany'); $sub->get ("users", null, 'userId'); $db->where (null, $sub, 'exists'); $products = $db->get ("products"); // Gives SELECT * FROM products WHERE EXISTS (SELECT userId FROM users WHERE company='testCompany') ``` -------------------------------- ### PHP Creating a Table Object Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/dbObject.md Shows how to create a dbObject instance for a database table either by using the `table()` method for simple cases or by defining a model class that extends `dbObject`. ```php $user = dbObject::table("users"); ``` ```php class user extends dbObject {} // If autoload is set to 'models' directory, the filename should be models/user.php // To change the table name, define correct name in the $dbTable variable: // protected $dbTable = "users"; ``` -------------------------------- ### PHP: OR WHERE, NULL Comparison, LIKE, and Raw Conditions Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Shows how to use `orWhere()` for OR conditions, compare against NULL values using 'IS NOT' or 'IS', perform LIKE comparisons, and use raw SQL strings for flexible condition building. Raw conditions can also include bind variables. ```php $db->where ('firstName', 'John'); $db->orWhere ('firstName', 'Peter'); $results = $db->get ('users'); // Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter' ``` ```php $db->where ("lastName", NULL, 'IS NOT'); $results = $db->get("users"); // Gives: SELECT * FROM users where lastName IS NOT NULL ``` ```php $db->where ("fullName", 'John%', 'like'); $results = $db->get("users"); // Gives: SELECT * FROM users where fullName like 'John%' ``` ```php $db->where ("id != companyId"); $db->where ("DATE(createdAt) = DATE(lastLogin)"); $results = $db->get("users"); ``` ```php $db->where ("(id = ? or id = ?)", Array(6,2)); $db->where ("login","mike"); $res = $db->get ("users"); // Gives: SELECT * FROM users WHERE (id = 6 or id = 2) and login='mike'; ``` -------------------------------- ### Include MysqliDb Manually Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to include the MysqliDb.php file directly into your PHP project. This is a manual approach to integrating the library. ```php require_once ('MysqliDb.php'); ``` -------------------------------- ### Benchmark Query Execution Time (PHP) Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Enables tracking of query execution time by calling the setTrace() function. It can optionally strip a prefix from the filename in the trace output. The output is an array containing query details, execution time, and file/line information. ```php $db->setTrace (true); // As a second parameter it is possible to define prefix of the path which should be striped from filename // $db->setTrace (true, $_SERVER['SERVER_ROOT']); $db->get("users"); $db->get("test"); print_r ($db->trace); ``` -------------------------------- ### Getting the Last Executed SQL Query in PHP-MySQLi Database Class Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to retrieve the last executed SQL query using `getLastQuery()`. This method is primarily for debugging purposes and should be used with caution, as the retrieved query might not be directly executable due to potential issues with variable quoting. ```php $db->get('users'); echo "Last executed query was ". $db->getLastQuery(); ``` -------------------------------- ### Add Multiple Database Connections Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to add additional database connections to MysqliDb, allowing the application to connect to multiple databases simultaneously. Connections are named for easy selection. ```php $db->addConnection('slave', Array ( 'host' => 'host', 'username' => 'username', 'password' => 'password', 'db'=> 'databaseName', 'port' => 3306, 'prefix' => 'my_', 'charset' => 'utf8') ); ``` -------------------------------- ### Set Table Prefix After Initialization Source: https://github.com/thingengineer/php-mysqli-database-class/blob/master/readme.md Demonstrates how to set the table prefix for MysqliDb after the object has been created. This allows dynamic prefix configuration. ```php $db->setPrefix ('my_'); ``` -------------------------------- ### HTML Form for Mission Data Input Source: https://github.com/thingengineer/php-mysqli-database-class/wiki/_Sidebar This HTML snippet defines a form that allows users to input data for a mission. It includes input fields for 'location', 'mission', and 'place', along with a select dropdown for 'voice' with predefined options. The form uses the POST method to send data to the server and includes 'Submit' and 'Clear' buttons. ```html