### MySQL DSN Examples for MeekroDB Source: https://meekro.com/docs/connection Provides various examples of Data Source Names (DSN) for connecting to MySQL databases, including host, port, dbname, and unix_socket configurations. ```PHP mysql:host=localhost;dbname=testdb mysql:host=localhost;port=3307;dbname=testdb mysql:unix_socket=/tmp/mysql.sock;dbname=testdb ``` -------------------------------- ### Configure SSL Connection Options for MeekroDB Source: https://meekro.com/docs/connection Shows how to set up SSL connection options for MySQL using PDO attributes. Examples are provided for both static and object-oriented MeekroDB modes. ```PHP $connect_options = [ PDO::MYSQL_ATTR_SSL_KEY => '', PDO::MYSQL_ATTR_SSL_CERT => '', PDO::MYSQL_ATTR_SSL_CA => '', PDO::MYSQL_ATTR_SSL_CAPATH => '' ]; // static mode DB::$connect_options = $connect_options; // object-oriented $db = new MeekroDB($dsn, $user, $password, $connect_options); ``` -------------------------------- ### DSN Examples for SQLite and PostgreSQL with MeekroDB Source: https://meekro.com/docs/connection Illustrates Data Source Name (DSN) formats for connecting MeekroDB to PostgreSQL and SQLite databases, including in-memory and file-based SQLite connections. ```PHP pgsql:host=localhost;port=5432;dbname=meekrodb sqlite: sqlite::memory: sqlite:/opt/databases/mydb.sq3 ``` -------------------------------- ### Get Table List with DB::tableList() Source: https://meekro.com/docs/misc-methods Retrieves an array of table names from the specified database. If no database name is provided, it defaults to the current database. The example demonstrates how to fetch and iterate through the table names. ```PHP $current_db_tables = DB::tableList(); $other_db_tables = DB::tableList('other_db'); foreach ($other_db_tables as $table) { echo "Table Name: $table\n"; } ``` -------------------------------- ### MeekroDB pre_run Hook Example Source: https://meekro.com/docs/hooks Demonstrates how to use the `pre_run` hook, which executes after query compilation but before execution. This hook can modify the query or its parameters, or simply log details, by returning an array of the modified query and parameters. ```PHP // this hook will change the query, adding "LIMIT 1" under certain circumstances $fn = function($hash) { $query = $hash['query']; $params = $hash['params']; $func_name = $hash['func_name']; // if the query is only asking for the first row, make sure it has a LIMIT if ($func_name == 'queryFirstRow' || $func_name == 'queryFirstField') { if (!substr_count($query, 'LIMIT')) { $query .= ' LIMIT 1'; } } return [$query, $params]; }; // this hook won't change the query, but will display it $fn2 = function($hash) { $query = $hash['query']; $params = $hash['params']; $func_name = $hash['func_name']; echo "QUERY: $query\n"; echo "PARAMS: [" . implode(',', $params) . "]\n"; }; DB::addHook('pre_run', $fn); DB::addHook('pre_run', $fn2); DB::queryFirstField("SELECT password FROM accounts WHERE id=%i", 1); // $fn2 will output: // QUERY: SELECT password FROM accounts WHERE id=? LIMIT 1 // PARAMS: [1] ``` -------------------------------- ### Standard Database Transaction Management with MeekroDB Source: https://meekro.com/docs/transactions Demonstrates how to use DB::startTransaction(), DB::commit(), and DB::rollback() to conditionally apply database changes. This example updates user passwords and commits only if more than 3 rows are affected, otherwise it rolls back. ```php // only keep the password change if >3 people were affected DB::startTransaction(); DB::query("UPDATE accounts SET password=%s WHERE password=%s", 'sdfwsert4rt', 'hello'); $counter = DB::affectedRows(); if ($counter > 3) { echo "$counter people just got their password changed!!\n"; DB::commit(); } else { echo "Too few people got their password changed!\n"; DB::rollback(); } ``` -------------------------------- ### PHP: Constructing Dynamic SQL WHERE Clauses with MeekroDB WhereClause Source: https://meekro.com/docs/whereclause This example demonstrates how to use the MeekroDB `WhereClause` class to dynamically build complex SQL WHERE conditions. It shows creating a clause, adding simple conditions, injecting the clause into `SELECT`, `DELETE`, and `UPDATE` queries, and managing sub-clauses with `addClause` and negation using `negateLast` and `negate`. ```PHP $where = new WhereClause('and'); // create a WHERE statement of pieces joined by ANDs $where->add('username=%s', 'Joe'); $where->add('password=%s', 'mypass'); // SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') $results = DB::query("SELECT * FROM accounts WHERE %?", $where); // DELETE FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') DB::delete('accounts', '%?', $where); // UPDATE accounts SET is_admin=1 WHERE (`username`='Joe') AND (`password`='mypass') DB::update('accounts', array('is_admin' => 1), '%?', $where); $subclause = $where->addClause('or'); // add a sub-clause with ORs $subclause->add('age=%i', 15); $subclause->add('age=%i', 18); $subclause->negateLast(); // negate the last thing added (age=18) // SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') AND ((`age`=15) OR (NOT(`age`=18))) $results = DB::query("SELECT * FROM accounts WHERE %?", $where); $subclause->negate(); // negate this entire subclause // SELECT * FROM accounts WHERE (`username`='Joe') AND (`password`='mypass') AND (NOT((`age`=15) OR (NOT(`age`=18)))) $results = DB::query("SELECT * FROM accounts WHERE %?", $where); ``` -------------------------------- ### Nested Transactions with MeekroDB using Savepoints Source: https://meekro.com/docs/transactions Illustrates how to enable and use nested transactions in MeekroDB with DB::$nested_transactions. It shows starting nested transactions, checking the transaction depth, and committing inner and outer transactions, which are internally managed with SAVEPOINTs. ```php DB::$nested_transactions = true; DB::startTransaction(); // .. some queries.. $depth = DB::startTransaction(); // start nested transaction echo "We are currently $depth transactions deep"; // 2 // .. some queries.. DB::commit(); // commit inner transaction // .. some queries.. DB::commit(); // commit outer transaction ``` -------------------------------- ### MeekroDB run_success Hook Example Source: https://meekro.com/docs/hooks Shows how to use the `run_success` hook, which is triggered exclusively when a query executes successfully. This hook provides details such as the query, its runtime, the number of rows returned, and affected rows, making it ideal for success-specific logging or post-query actions. ```PHP $fn = function($hash) { $query = $hash['query']; $runtime = $hash['runtime']; // runtime in ms $rows = $hash['rows']; // number of rows returned (does not apply for queryWalk()) $affected = $hash['affected']; // affected rows (for insert/update/delete) $func_name = $hash['func_name']; echo "QUERY: $query ($runtime ms)\n"; echo "ROWS RETURNED: $rows\n"; echo "AFFECTED ROWS: $affected\n"; } DB::addHook('run_success', $fn); DB::query("SELECT * FROM accounts"); ``` -------------------------------- ### Get Last Executed Query with DB::lastQuery() Source: https://meekro.com/docs/misc-methods Retrieves the last SQL query that was executed by MeekroDB. This method is useful for debugging and logging, as it returns the query string regardless of whether the execution succeeded or failed. ```PHP $query = DB::lastQuery(); ``` -------------------------------- ### Get Column List with DB::columnList() Source: https://meekro.com/docs/misc-methods Fetches an array of column details for a given table within the current database. The returned array provides comprehensive information for each column, including its type, nullability, key status, default value, and any extra attributes. ```PHP $columns = DB::columnList('accounts'); foreach ($columns as $name => $details) { echo "Column: $name\n"; echo "Type: " . $details['type'] . "\n"; echo "Null? " . $details['null'] . "\n"; echo "Key: " . $details['key'] . "\n"; echo "Default: " . $details['default'] . "\n"; echo "Extra: " . $details['extra'] . "\n"; } ``` -------------------------------- ### Change Parameter Character with DB::$param_char Source: https://meekro.com/docs/misc-methods Modifies the character used to denote parameters in MeekroDB queries. The default parameter character is `%`. This example demonstrates how to change it to a colon (`:`), affecting how parameters are specified in subsequent queries. ```PHP DB::$param_char = ':'; $results = DB::query("SELECT * FROM accounts WHERE email=:s", '[email protected]'); ``` -------------------------------- ### MeekroDB post_run Hook Example Source: https://meekro.com/docs/hooks Illustrates the `post_run` hook, which runs after a query has been executed, regardless of success or failure. It provides comprehensive details including query, runtime, affected rows, and any error messages or exceptions, enabling robust logging and error handling. ```PHP $fn = function($hash) { $query = $hash['query']; $runtime = $hash['runtime']; // runtime in ms $rows = $hash['rows']; // number of rows returned (does not apply for queryWalk()) $affected = $hash['affected']; // affected rows (for insert/update/delete) $func_name = $hash['func_name']; $error = $hash['error']; // error message, if any $Exception = $hash['exception']; // if error, this exception will be thrown after the hooks run echo "QUERY: $query ($runtime ms)\n"; echo "ERROR: $error\n"; } DB::addHook('post_run', $fn); // this broken query will cause the $error and $Exception to be set in the hook DB::query("SELCT * FROM accounts"); // this successful query will have $error and $Exception as null, but $rows will be set DB::query("SELECT * FROM accounts"); ``` -------------------------------- ### Get Database Type with DB::dbType() Source: https://meekro.com/docs/misc-methods Returns a string indicating the type of the database currently connected. Possible return values include 'mysql', 'sqlite', or 'pgsql', allowing for conditional logic based on the database system. ```PHP $type = DB::dbType(); echo "We are connected to a $type database!"; ``` -------------------------------- ### Retrieve First Field with DB::queryFirstField Source: https://meekro.com/docs/retrieving-data Gets the value of the first field from the first row of a query result. Returns null if no rows are found. Useful for fetching a single specific piece of data, like a password or a count. ```PHP $joePassword = DB::queryFirstField("SELECT password FROM accounts WHERE username=%s", 'Joe'); echo "Joe's password is: " . $joePassword . "\n"; ``` -------------------------------- ### Retrieve First Column as Array with DB::queryFirstColumn Source: https://meekro.com/docs/retrieving-data Extracts all values from the first column of a query result into a regular array. Returns an empty array if no rows are found. Useful for getting a list of distinct values or IDs from a table. ```PHP $usernames = DB::queryFirstColumn("SELECT DISTINCT username FROM accounts"); foreach ($usernames as $username) { echo "Username: " . $username . "\n"; } ``` -------------------------------- ### MeekroDB run_failed Hook Example Source: https://meekro.com/docs/hooks Demonstrates the `run_failed` hook, which activates only when a query fails. This hook provides access to the query, runtime, error message, and the exception object, allowing for custom error logging or even suppressing the default exception if the hook returns false. ```PHP $fn = function($hash) { $query = $hash['query']; $runtime = $hash['runtime']; // runtime in ms $func_name = $hash['func_name']; $error = $hash['error']; // error message $Exception = $hash['exception']; // this exception will be thrown after hooks run echo "QUERY: $query ($runtime ms)\n"; echo "ERROR: $error\n"; } DB::addHook('run_failed', $fn); DB::query("SELCT * FROM accounts"); // run_failed hook will receive: // $error: "You have an error in your SQL syntax..." ``` -------------------------------- ### Change Named Parameter Separator with DB::$named_param_seperator Source: https://meekro.com/docs/misc-methods Alters the character that separates the name for named parameters, especially when `DB::$param_char` has also been changed. The default separator is `_`. This example illustrates how to customize both the parameter character and the named parameter separator for more flexible query syntax. ```PHP DB::$param_char = ':'; DB::$named_param_seperator = '@'; $results = DB::query("SELECT * FROM accounts WHERE email=:s@email", ['email' => '[email protected]']); ``` -------------------------------- ### Connect to MySQL in Static Mode using MeekroDB Source: https://meekro.com/docs/connection Demonstrates how to configure MeekroDB for database connection in static mode by setting DSN, username, and password. The connection is established on the first query. ```PHP DB::$dsn = 'mysql:host=localhost;dbname=my_database_name'; DB::$user = 'my_database_user'; DB::$password = 'my_database_password'; // run your first query? DB::query("SELECT * FROM tbl"); ``` -------------------------------- ### API Documentation for Miscellaneous Methods and Variables in MeekroDB Source: https://meekro.com/docs/index This section covers various utility methods and static variables within MeekroDB that provide additional functionality. These include methods for database selection, listing tables/columns, disconnecting, retrieving last queries, and configuring parameter parsing. ```APIDOC DB::useDB() ``` ```APIDOC DB::tableList() ``` ```APIDOC DB::columnList() ``` ```APIDOC DB::disconnect() ``` ```APIDOC DB::get() ``` ```APIDOC DB::lastQuery() ``` ```APIDOC DB::parse() ``` ```APIDOC DB::$param_char ``` ```APIDOC DB::$named_param_seperator ``` ```APIDOC DB::$reconnect_after ``` -------------------------------- ### Connect to MySQL in Object-Oriented Mode using MeekroDB Source: https://meekro.com/docs/connection Illustrates how to establish a database connection using MeekroDB's object-oriented approach. A new MeekroDB instance is created with DSN, user, and password, and the connection is made on the first query. ```PHP $dsn = 'mysql:host=localhost;dbname=my_database_name'; $user = 'my_database_user'; $password = 'my_database_password'; $db = new MeekroDB($dsn, $user, $password); // run your first query? $db->query("SELECT * FROM tbl"); ``` -------------------------------- ### API Documentation for Connecting to MeekroDB Source: https://meekro.com/docs/index This section outlines the properties used for configuring the database connection in MeekroDB, including DSN, user credentials, and connection options. These static properties of the DB class allow for global configuration of database access. ```APIDOC DB::$dsn ``` ```APIDOC DB::$user ``` ```APIDOC DB::$password ``` ```APIDOC DB::$connect_options ``` -------------------------------- ### API Documentation for Retrieving Data with MeekroDB Source: https://meekro.com/docs/index This section details the methods available in MeekroDB for fetching data from the database. It includes functions for executing queries and retrieving results in various formats, such as single rows, fields, lists, or columns. ```APIDOC DB::query() ``` ```APIDOC DB::queryFirstRow() ``` ```APIDOC DB::queryFirstField() ``` ```APIDOC DB::queryFirstList() ``` ```APIDOC DB::queryFirstColumn() ``` ```APIDOC DB::queryFullColumns() ``` ```APIDOC DB::queryWalk() ``` -------------------------------- ### API Documentation for Hooks with MeekroDB Source: https://meekro.com/docs/index This section outlines MeekroDB's hook system, allowing developers to inject custom logic at various points in the database operation lifecycle. It includes methods for adding, removing, and clearing hooks. ```APIDOC DB::addHook() ``` ```APIDOC DB::removeHook() ``` ```APIDOC DB::removeHooks() ``` -------------------------------- ### MeekroDB: Placeholder Reference Source: https://meekro.com/docs/retrieving-data This API documentation provides a comprehensive list of all available placeholders in MeekroDB, detailing their meaning and intended use cases for secure and flexible SQL query construction. ```APIDOC Placeholder | Meaning --- %s | string %i | integer %d | decimal/double %t | timestamp (can be instance of DateTime or string accepted by strtotime) %? | auto-detect data type %ss | search string (string surrounded with % for use with LIKE) %b | backticks (do not use with user-supplied data) %l | literal (do not use with user-supplied data) %ls | list of strings %li | list of integers %ld | list of decimals/doubles %lt | list of timestamps %lb | list of backticks (do not use with user-supplied data) %% | literal % character ``` -------------------------------- ### API Documentation for Transactions with MeekroDB Source: https://meekro.com/docs/index This section details MeekroDB's capabilities for managing database transactions. It provides methods to initiate, commit, and rollback transactions, ensuring data integrity for multi-step operations. It also covers nested transaction behavior. ```APIDOC DB::startTransaction() ``` ```APIDOC DB::commit() ``` ```APIDOC DB::rollback() ``` ```APIDOC DB::$nested_transactions ``` -------------------------------- ### API Documentation for Debug Logging with MeekroDB Source: https://meekro.com/docs/index This section describes how to configure debug logging in MeekroDB. It specifically highlights the static property used to define a log file for recording database operations and errors, aiding in troubleshooting and development. ```APIDOC DB::$logfile ``` -------------------------------- ### Prepare Partial Query with DB::parse() Source: https://meekro.com/docs/misc-methods Prepares a partial SQL query, allowing it to be used as a parameter within a larger query using `%?` or `%l`. This feature facilitates building complex queries from modular components, where each component can have its own parameters. ```PHP $part = DB::parse("WHERE name=%s AND age=%i", 'Joe', 15); $results = DB::query("SELECT * FROM accounts %?", $part); // SELECT * FROM accounts WHERE name='Joe' AND age=15 ``` -------------------------------- ### MeekroDB: Execute SQL Query with Positional Placeholders Source: https://meekro.com/docs/retrieving-data Demonstrates how to execute a SQL query using DB::query() with various positional placeholders for strings, integers, and decimals. It also shows how to iterate through the results, which are returned as an array of associative arrays. ```PHP // no placeholders DB::query("SELECT * FROM tbl"); // string, integer, and decimal placeholders $results = DB::query("SELECT * FROM tbl WHERE name=%s AND age > %i AND height <= %d", $name, 15, 13.75); foreach ($results as $row) { echo "Name: " . $row['name'] . "\n"; echo "Age: " . $row['age'] . "\n"; echo "Height: " . $row['height'] . "\n"; echo "-------------\n"; } ``` -------------------------------- ### MeekroDB: Execute SQL Query with Named Placeholders Source: https://meekro.com/docs/retrieving-data Shows how to use named parameters with DB::query(). Instead of positional arguments, an associative array of named parameters is passed, allowing for more readable and maintainable queries, especially with many parameters. ```PHP DB::query("SELECT * FROM tbl WHERE name=%s_name AND age > %i_age AND height <= %d_height", [ 'name' => $name, 'age' => 15, 'height' => 13.75 ] ); ``` -------------------------------- ### MeekroDB: Execute SQL Query with List Placeholders Source: https://meekro.com/docs/retrieving-data Demonstrates the use of list placeholders (%ls for string lists, %li for integer lists) with DB::query(). These are particularly useful for IN or NOT IN clauses, allowing an array of values to be safely inserted into the query. ```PHP $results = DB::query("SELECT * FROM tbl WHERE name IN %ls AND age NOT IN %li", ['John', 'Bob'], [12, 15]); ``` -------------------------------- ### Configure MeekroDB to Log Queries to Screen Output Source: https://meekro.com/docs/logging This PHP snippet configures MeekroDB to output all database queries and errors directly to the screen (standard output). This is useful for debugging during development but should not be used in production environments. ```PHP DB::$logfile = fopen('php://output', 'w'); ``` -------------------------------- ### MeekroDB: Execute SQL Query with Out-of-Order and Repeated Positional Placeholders Source: https://meekro.com/docs/retrieving-data Illustrates advanced usage of DB::query() where parameters can be referenced out of order by adding a number to the placeholder (e.g., %s2). It also shows how to refer to the same parameter multiple times within a single query. ```PHP // use the parameter number to refer to parameters out of order DB::query("SELECT * FROM tbl WHERE name=%s2 AND age > %i0 AND height <= %d1", 15, 13.75, $name); // refer to the same parameter twice DB::query("SELECT * FROM tbl WHERE firstname=%s0 AND lastname=%s0", 'John'); ``` -------------------------------- ### Configure MeekroDB to Log Queries to a File Source: https://meekro.com/docs/logging This PHP snippet sets the MeekroDB log file path to a specified file, directing all database queries and errors to be recorded there. Ensure the web server has write permissions to the specified directory and file. ```PHP DB::$logfile = '/home/username/logfile.txt'; ``` -------------------------------- ### API Documentation for Inserting and Altering Data with MeekroDB Source: https://meekro.com/docs/index This section covers MeekroDB's methods for modifying data within the database. It includes functions for inserting new records, updating existing ones, deleting entries, and retrieving information about affected rows or last insert IDs. ```APIDOC DB::insert() ``` ```APIDOC DB::insertId() ``` ```APIDOC DB::insertIgnore() ``` ```APIDOC DB::insertUpdate() ``` ```APIDOC DB::replace() ``` ```APIDOC DB::update() ``` ```APIDOC DB::delete() ``` ```APIDOC DB::affectedRows() ``` -------------------------------- ### Iterate Large Datasets with DB::queryWalk Source: https://meekro.com/docs/retrieving-data Provides an iterator for large datasets that cannot be loaded into memory entirely. Allows processing results row by row, making it suitable for big data operations. It's crucial to call `free()` if not all results are consumed to prevent issues with subsequent queries. ```PHP $Walk = DB::queryWalk("SELECT * FROM bigtable"); while ($row = $Walk->next()) { var_dump($row); // assoc array for one row } ``` ```PHP $Walk = DB::queryWalk("SELECT * FROM bigtable"); $firstrow = $Walk->next(); // we actually only want one row! $Walk->free(); // free remaining results ``` -------------------------------- ### Retrieve PDO Object with DB::get() Source: https://meekro.com/docs/misc-methods Returns the underlying PDO (PHP Data Objects) instance that MeekroDB uses for database interactions. This allows direct access to PDO functionalities for advanced use cases. ```PHP $pdo = DB::get(); ``` -------------------------------- ### MeekroDB: Retrieve First Row with DB::queryFirstRow() Source: https://meekro.com/docs/retrieving-data Demonstrates the DB::queryFirstRow() method, which retrieves only the first matching row from a query result. It returns the row as an associative array or null if no rows are found, simplifying single-record lookups. ```PHP $account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe'); echo "Username: " . $account['username'] . "\n"; // will be Joe, obviously echo "Password: " . $account['password'] . "\n"; ``` -------------------------------- ### Retrieve First Row as List with DB::queryFirstList Source: https://meekro.com/docs/retrieving-data Fetches the first row of a query result as a numerically indexed array. Returns null if no rows are found. Ideal for destructuring a single row into multiple variables when the column order is known. ```PHP list($username, $password) = DB::queryFirstList("SELECT username, password FROM accounts WHERE username=%s", 'Joe'); echo "Username: " . $username . "\n"; // will be Joe, obviously echo "Password: " . $password . "\n"; ``` -------------------------------- ### Configure Reconnection Timeout with DB::$reconnect_after Source: https://meekro.com/docs/misc-methods Sets the minimum time (in seconds) that must elapse since the last query before MeekroDB attempts to re-connect to the database. This variable helps manage database connections, particularly in environments with `wait_timeout` settings like MySQL. The default value is 4 hours. ```PHP // if MySQL was configured with a wait_timeout of 60 seconds, we should set // our reconnect to 30 seconds like this DB::$reconnect_after = 30; ``` -------------------------------- ### MeekroDB: Handling Literal Percentage Characters in Queries Source: https://meekro.com/docs/retrieving-data Explains how to include a literal '%' character in SQL queries when using MeekroDB. If the query has no parameters, '%' can be used directly. If parameters are present, '%%' must be used to escape the literal percentage sign. ```PHP // this query has no parameters, so % works as normal DB::queryFirstField("SELECT DATE_FORMAT('2009-10-04 22:23:00', '%H:%i:%s')"); // this query has one parameter (15), so % characters have been escaped DB::queryFirstField("SELECT DATE_FORMAT(created_at, '%%H:%%i:%%s')\n FROM accounts WHERE id=%i", 15); ``` -------------------------------- ### Retrieve Full Columns with Table Names using DB::queryFullColumns Source: https://meekro.com/docs/retrieving-data Similar to `DB::query()`, but returns associative array keys in 'TableName.ColumnName' format. This is particularly useful when joining multiple tables that might have identically named columns, preventing naming conflicts and clarifying data origin. ```PHP $joe = DB::queryFullColumns("SELECT * FROM accounts WHERE username=%s", 'Joe'); print_r($joe); /* Returns something like: Array ( [accounts.id] => 3 [accounts.username] => Joe [accounts.password] => whatever ) */ ``` -------------------------------- ### Disconnect MySQL Connection with DB::disconnect() Source: https://meekro.com/docs/misc-methods Drops any existing MySQL connections managed by MeekroDB. If a query is executed after calling this method, MeekroDB will automatically re-establish a connection as needed. ```PHP DB::disconnect(); // drop connection ``` -------------------------------- ### Insert into a different database using DB::insert() in PHP Source: https://meekro.com/docs/altering-data Allows inserting data into a table in a different database by specifying the database and table name as an array for the first argument. This functionality applies to other MeekroDB methods accepting a table name. ```PHP DB::insert(['mydb', 'accounts'], [ 'username' => 'Joe', 'password' => 'hello' ]); ``` -------------------------------- ### Perform REPLACE using DB::replace() in PHP Source: https://meekro.com/docs/altering-data Works just like INSERT, but executes a REPLACE statement. This means if a row with the same primary or unique key exists, it will be deleted and a new row inserted. Returns the number of rows inserted. ```PHP // change Joe's password (assuming username is a primary key) DB::replace('accounts', [ 'username' => 'Joe', 'password' => 'asd254890s' ]); ``` -------------------------------- ### Insert with placeholder variables in DB::sqleval() in PHP Source: https://meekro.com/docs/altering-data Enables the use of placeholder variables within DB::sqleval() for dynamic SQL function arguments. This ensures proper escaping of the variables before they are passed to the SQL function. ```PHP DB::insert('accounts', [ 'username' => 'Joe', 'password' => 'hello', 'data' => DB::sqleval("REPEAT('blah', %i)", 4) ]); ``` -------------------------------- ### Disable MeekroDB Query Logging Source: https://meekro.com/docs/logging This PHP snippet disables all query logging for MeekroDB by setting the logfile variable to null. This stops MeekroDB from writing query information to any file or output stream. ```PHP DB::$logfile = null; ``` -------------------------------- ### Insert with SQL functions using DB::sqleval() in PHP Source: https://meekro.com/docs/altering-data Allows embedding SQL functions directly into insert statements without escaping them. Wrap the SQL function call with DB::sqleval() to ensure it's evaluated by the database. ```PHP DB::insert('accounts', [ 'username' => 'Joe', 'password' => 'hello', 'created_at' => DB::sqleval("NOW()") ]); ``` -------------------------------- ### MeekroDB Hook Management API Source: https://meekro.com/docs/hooks API methods for adding, removing, and managing custom hook functions in MeekroDB. Hooks are identified by type and a unique ID returned upon addition. ```APIDOC $hook_id = DB::addHook(string $hook_type, callable $fn) Description: Adds a custom hook function to be executed at a specific stage. Parameters: $hook_type (string): The type of hook (e.g., 'pre_run', 'post_run'). $fn (callable): The function to be executed as the hook. It receives a hash of query details. Returns: int - A unique ID for the added hook, used for removal. DB::removeHook(string $hook_type, int $hook_id) Description: Removes a specific hook previously added with DB::addHook(). Parameters: $hook_type (string): The type of the hook to remove. $hook_id (int): The ID of the hook to remove, obtained from DB::addHook(). DB::removeHooks(string $hook_type) Description: Removes all hooks of a specified type. Parameters: $hook_type (string): The type of hooks to remove (e.g., 'pre_run'). ``` -------------------------------- ### Using DB::affectedRows() to Count Modified Rows Source: https://meekro.com/docs/altering-data This snippet demonstrates how to execute an UPDATE query and then immediately retrieve the number of affected rows using DB::affectedRows(). This function is useful for verifying the impact of DML operations like UPDATE, INSERT, or DELETE. ```PHP DB::query("UPDATE accounts SET password=%s WHERE password=%s", 'sdfwsert4rt', 'hello'); $counter = DB::affectedRows(); echo $counter . " people just got their password changed!!\n"; ``` -------------------------------- ### Insert multiple rows using DB::insert() in PHP Source: https://meekro.com/docs/altering-data Inserts multiple rows into the specified table by passing an array of associative arrays. It returns the number of rows inserted. ```PHP $rows = []; $rows[] = [ 'username' => 'Frankie', 'password' => 'abc' ]; $rows[] = [ 'username' => 'Bob', 'password' => 'def' ]; DB::insert('accounts', $rows); ``` -------------------------------- ### Delete data using DB::delete() in PHP Source: https://meekro.com/docs/altering-data Provides a convenient way to perform DELETE operations. It offers similar functionality to DB::query() for deletions, simplifying common delete patterns. Returns the number of affected rows. ```PHP DB::delete('tbl', 'username=%s', $name); DB::delete('tbl', ['username' => $name]); DB::query("DELETE FROM tbl WHERE username=%s", $name); ``` -------------------------------- ### Update data using DB::update() in PHP Source: https://meekro.com/docs/altering-data Provides a convenient way to perform UPDATE operations. It offers similar functionality to DB::query() for updates, simplifying common update patterns. Returns the number of affected rows. ```PHP DB::update('tbl', ['age' => 25, 'height' => 10.99], "name=%s", $name); DB::update('tbl', ['age' => 25, 'height' => 10.99], ['name' => $name]); DB::query("UPDATE tbl SET age=%i, height=%d WHERE name=%s", 25, 10.99, $name); ``` -------------------------------- ### Perform INSERT ... ON DUPLICATE KEY UPDATE using DB::insertUpdate() in PHP Source: https://meekro.com/docs/altering-data Executes an INSERT ... ON DUPLICATE KEY UPDATE statement. If a primary key is duplicated, the specified fields are updated. Returns the number of rows inserted or affected. Note: Not supported by SQLite or Postgres. ```PHP DB::insertUpdate('accounts', [ 'id' => 5, 'username' => 'Joe', 'password' => 'hello' ], 'password=%s', 'hello'); ``` -------------------------------- ### Perform INSERT IGNORE using DB::insertIgnore() in PHP Source: https://meekro.com/docs/altering-data Executes an INSERT IGNORE statement, preventing MySQL errors if a primary key is already taken. It returns the number of rows inserted. Note: This method is not supported by SQLite or Postgres. ```PHP DB::insertIgnore('accounts', [ 'id' => 5, 'username' => 'Joe', 'password' => 'hello' ]); ``` -------------------------------- ### Perform INSERT ... ON DUPLICATE KEY UPDATE with assoc array using DB::insertUpdate() in PHP Source: https://meekro.com/docs/altering-data Allows specifying a second associative array for update fields when a primary key is duplicated. This provides fine-grained control over which fields are updated upon a duplicate key conflict. ```PHP DB::insertUpdate('accounts', [ 'id' => 5, 'username' => 'Joe', 'password' => 'hello' ], [ 'password' => 'goodbye' ]); ``` -------------------------------- ### Perform INSERT ... ON DUPLICATE KEY UPDATE with single assoc array using DB::insertUpdate() in PHP Source: https://meekro.com/docs/altering-data If only a single associative array is passed, all its values will be updated if the primary key is taken, similar to a REPLACE INTO statement. This updates all fields provided in the initial array upon conflict. ```PHP DB::insertUpdate('accounts', [ 'id' => 5, 'username' => 'Joe', 'password' => 'hello' ]); ``` -------------------------------- ### Insert a single row using DB::insert() in PHP Source: https://meekro.com/docs/altering-data Inserts a single row into the specified table. It returns the number of rows inserted. The method takes the table name and an associative array of column-value pairs. ```PHP DB::insert('accounts', [ 'username' => 'Joe', 'password' => 'hello' ]); ``` -------------------------------- ### Retrieve last insert ID using DB::insertId() in PHP Source: https://meekro.com/docs/altering-data Returns the auto-incrementing ID generated by the last INSERT statement. This is useful for retrieving the primary key of a newly inserted row immediately after insertion. ```PHP // accounts.id is an auto-incrementing column DB::insert('accounts', array( 'username' => 'Joe', 'password' => 'hello' )); $joe_id = DB::insertId(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.