Basic data operation
The database operation of micro engine system uses PDO compatible mode to query in the form of parameter binding.
The system has tested and encapsulated PDO compatibility. The following describes several basic operation methods of the database.
tablename()
In order to prevent the naming conflict between the table of the micro engine system and other systems, a table prefix will be specified when installing the micro engine. When writing SQL statements, the table name needs to be appended with the table prefix. You can use the tablename() function.
$sql = "SELECT * FROM ".tablename('users'); echo $sql; //Output SELECT * FROM ims_users
Range condition operation
PDO has been added in the version after micro engine 20160601_ get,pdo_getall,pdo_getcolumn,pdo_getslice,pdo_insert,pdo_update,pdo_ The range condition of delete is supported. The specific range operators supported are as follows:
$allow_operator = array('>', '<', '<>', '!=', '>=', '<=', '+=', '-=', 'LIKE', 'like');
Example:
//Obtain a platform account with an acid greater than 269 $account = pdo_get('account', array('acid >' => '269')); //Increase the number of false logins of the user once, and change it to 2 twice pdo_update('users_failed_login', array('count +=' => 1), array('username' => 'mizhou'));
IN and NOT IN
When the value of the passed IN condition array is an array, the system will automatically convert it into an IN statement, if and < > or= (not equal to) is automatically converted to NOT IN when used together.
Example:
pdo_getall('users', array('uid' => array('1', '2', '3'))); //Corresponding SQL statement call pdo_fetchall("SELECT * FROM `ims_users` WHERE `uid` IN (:__uid_0,:__uid_1,:__uid_2)", array(':__uid_0' => 1, ':__uid_1' => 2, ':__uid_2' => 3));
pdo_getall('users', array('uid <>' => array('1', '2', '3'))); //Corresponding SQL statement call pdo_fetchall("SELECT * FROM `ims_users` WHERE `uid` NOT IN (:__uid_0,:__uid_1,:__uid_2)", array(':__uid_0' => 1, ':__uid_1' => 2, ':__uid_2' => 3));
IS NULL and IS NOT NULL
When and only when the value is an uppercase NULL string, the system will think that it is necessary to query the NULL value, and the SQL will be written in the form of IS NULL, as follows:
pdo_get('users', array('username' => 'NULL')); //This sentence will translate into SELECT * FROM user WHERE username IS NULL
Aggregate query
When the obtained fields are aggregate fields, such as COUNT(*), SUM(), if an alias is specified, the value can be obtained through the alias. If no alias is specified, the value can be obtained through the index sorted by the field.
Example:
$usercount = pdo_get('users', array(), array('COUNT(*)', 'uid', 'MAX(uid)', 'MIN(uid) AS minuid')); //$usercount value is Array ( [0] => 103 //total [uid] => 1 [2] => 179 //Maximum UID [minuid] => 1 //Minimum UID )
Chain query
Chained queries only support some common simple queries and complex business requirements. It is recommended to use SQL statements directly.
Query the first ten male user data in the user table, and the code is as follows:
$query = load()->object('query'); $row = $query->from('users')->where('type', '1')->orderby('uid', 'desc')->limit(10)->getall();
PDOS of database functions_ XXX function list
query
- pdo_get
- pdo_getcolumn
- pdo_getall
- pdo_getslice
- pdo_fetch
- pdo_fetchcolumn
- pdo_fetchall
change
- pdo_insert
- pdo_update
- pdo_delete
Run SQL
- pdo_query
- pdo_run
auxiliary function
- pdo_exists
- pdo_fieldexists
- pdo_indexexists
- pdo_tableexists
- pdo_fieldmatch
- pdo_insertid
- pdo_fetchallfields
- pdo_debug
pdo_get()
Get a record in the specified table according to the condition (AND connection)
explain
array | boolean pdo_get($tablename, $condition = array(), $fields = array());
parameter
- The $tablename} parameter specifies the name of the data table to be queried. The tablename() function is not used for the table name passed in here
- The $condition parameter specifies the query condition, so that it is an "AND" connection, AND supports queries in the range of greater than AND less than
- The $fields parameter specifies the list of fields returned by the query
Examples
//Obtain user name and user Id information according to uid //The generated SQL is equivalent to: SELECT username, uid FROM ims_users WHERE uid = '1' LIMIT 1 $user = pdo_get('users', array('uid' => 1), array('username', 'uid')); //The generated SQL is equivalent to: SELECT username FROM ims_users WHERE username like '%mizhou%' AND status = '1' LIMIT 1 $user = pdo_get('users', array('username like' => 'mizhou', 'status' => 1), array('username'));
pdo_getcolumn()
Gets the specified field of a record in the specified table according to the condition (AND connection)
explain
string | int pdo_getcolumn($tablename, $condition = array(), $field);
parameter
- The $tablename # parameter specifies the name of the data table to be queried. Do not use the tablename() function for the table name passed in here
- The $condition parameter specifies the query condition, so that it is an "AND" connection, AND supports queries in the range of greater than AND less than
- $field - name of the field to get
Examples
//Get the user name according to uid //The generated SQL is equivalent to: SELECT username FROM ims_users WHERE uid = '1' LIMIT 1 $username = pdo_getcolumn('users', array('uid' => 1), 'username');
pdo_getall()
Get all records in the specified table according to the condition (AND connection)
explain
array | boolean pdo_getall($tablename, $condition = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array());
parameter
- The $keyfield parameter passes in an existing field name, and the key value of the resulting array is the field. Otherwise, it is natural sorting
- $orderby sorted by xxx ascending / descending
- $limit paging, array (current page, pages per page)
- Other parameters are the same as pdo_get function
Examples
//Get all enabled users //The generated SQL is equivalent to: SELECT `username`,`uid` FROM `ims_users` WHERE `status` = 2 ORDER BY `starttime` desc,`endtime` desc LIMIT 0, 5 $user = pdo_getall('users', array('status' => 2), array('username', 'uid'), 'uid', array('starttime desc', 'endtime desc'), array(1,5));
pdo_getslice()
According to the condition (AND connection) to the specified table, obtain the records of a certain interval
explain
array | boolean pdo_getslice($tablename, $condition = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array());
parameter
- The $LIMIT parameter specifies the LIMIT value of the query statement, array(start, end) or directly pass in the range 2,3
- The $total , parameter specifies the total number of query results to facilitate paging operations
- Other parameters are the same as pdo_get,pdo_getall function
Examples
$user = pdo_getslice('users', array(), array(0, 10), $total, array('username', 'uid'), 'uid', array('starttime desc', 'endtime desc')); echo $total;
pdo_fetch()
Query a record according to the SQL statement
explain
array | boolean pdo_fetch($sql, $params = array());
parameter
- The $SQL parameter specifies the SQL statement to return the recordset
- The $params parameter is specified as the parameter binding value in the SQL statement to prevent SQL injection
It should be noted that when parameter binding is used, quotation marks do not need to be used after the equal sign in SQL language, and the passed in value must be consistent with the binding name
Examples
// : uid is a placeholder for a parameter without quotation marks. The second parameter passed in should be the same as the placeholder name in SQL $user = pdo_fetch("SELECT username, uid FROM ".tablename('users')." WHERE uid = :uid LIMIT 1", array(':uid' => 1)); // Usage of LIKE placeholder $user = pdo_fetch("SELECT * FROM ".tablename('users')." WHERE username LIKE :username", array(':username' => '%mizhou%'));
pdo_fetchcolumn()
Query the value of column N of the first record according to the SQL statement. This statement is similar to pdo_fetch uses the same, except that this function returns not an array but a string
explain
string | boolean pdo_fetchcolumn($sql, $params = array(), $column = 0);
parameter
- The $SQL parameter specifies the SQL statement to return the recordset
- The $params parameter is specified as the parameter binding value in the SQL statement to prevent SQL injection
It should be noted that when parameter binding is used, quotation marks do not need to be used after the equal sign in the SQL statement, and the passed in value must be consistent with the binding name - The $column parameter specifies which column of data to return from the recordset
Examples
// Gets the total number of users. The returned value is a number $user_total = pdo_fetchcolumn("SELECT COUNT(*) FROM ".tablename('users'));
pdo_fetchall()
Query all records according to the SQL statement. The usage method is the same as PDO_ Same as fetch
explain
array | boolean pdo_fetchall($sql, $params = array(), $keyfield = '');
parameter
- The $SQL parameter specifies the SQL statement to return the recordset
- The $params parameter is specified as the parameter binding value in the SQL statement to prevent SQL injection
It should be noted that when parameter binding is used, quotation marks do not need to be used after the equal sign in SQL language, and the passed in value must be consistent with the binding name - The $keyfield parameter passes in an existing field name, and the key value of the resulting array is the field, otherwise it is natural sorting
Examples
// Note that the key value of the returned array is the user's uid $user = pdo_fetchall("SELECT username, uid FROM ".tablename('users'), array(), 'uid');
pdo_insert()
Inserts a new record into the specified data table
explain
int | boolean pdo_insert($tablename, $data = array(), $replace = false);
parameter
- The $tablename} parameter specifies the name of the data table into which the record is to be inserted. Do not use the tablename() function for the table name passed in here
- The $data parameter specifies the record to be inserted in the format of an associative array corresponding to the data table field
- The $REPLACE parameter specifies the insertion method. Use the INSERT statement or REPLACE statement (select update if the data with the same primary key is found)
Examples
//Add a user record and judge whether it is successful $user_data = array( 'username' => 'mizhou1', 'status' => '1', ); $result = pdo_insert('users', $user_data); if (!empty($result)) { $uid = pdo_insertid(); message('User added successfully, UID by' . $uid); }
pdo_update()
Updates the records of the specified data table
explain
array | boolean pdo_update($tablename, $data = array(), $condition, $glue = 'AND')
parameter
- The $tablename} parameter specifies the name of the data table into which the record is to be inserted. Do not use the tablename() function for the table name passed in here
- The $data parameter specifies the record to be inserted in the format of an associative array corresponding to the data table field
- The $condition parameter specifies the precondition to update
- The $glue , parameter specifies the associated word AND OR of the previous $condition array condition
Examples
//The user name of the user whose uid is equal to 2 $user_data = array( 'username' => 'mizhou2', ); $result = pdo_update('users', $user_data, array('uid' => 2)); if (!empty($result)) { message('Update succeeded'); }
pdo_delete()
Delete data for specified conditions
explain
int | boolean pdo_delete($tablename, $condition = array(), $glue = 'AND')
parameter
- The $tablename} parameter specifies the name of the data table into which the record is to be inserted. Do not use the tablename() function for the table name passed in here
- The $condition parameter specifies the query condition, which is connected by AND. Queries with a range greater than AND less than are supported
- The $glue , parameter specifies the associated word AND OR of the previous $condition array condition
Examples
//Delete the record with user name mizhou2 $result = pdo_delete('users', array('username' => 'mizhou2')); if (!empty($result)) { message('Deleted successfully'); }
pdo_query()
Execute a non query statement
explain
int | boolean pdo_query($sql, $params = array())
parameter
- $params - specifies the value of the binding parameter in the SQL statement, and the parameter occupation is the same as pdo_fetch consistent
Examples
//The user name of the user whose uid is equal to 2 $result = pdo_query("UPDATE ".tablename('users')." SET username = :username, age = :age WHERE uid = :uid", array(':username' => 'mizhou2', ':age' => 18, ':uid' => 2)); //Delete the record with user name mizhou2 $result = pdo_query("DELETE FROM ".tablename('users')." WHERE uid = :uid", array(':uid' => 2)); if (!empty($result)) { message('Deleted successfully'); }
pdo_run()
Batch execution of SQL statements
explain
boolean pdo_run($sql, $stuff = 'ims_')
parameter
- The $stuff function will replace the value specified by this parameter with the table prefix of the current system.
Note: and pdo_query is different from pdo_run means that multiple SQL statements can be executed at one time, and each SQL statement must be executed in; separate.
Examples
$sql = <<<EOF CREATE TABLE IF NOT EXISTS `ims_multisearch` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `weid` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `ims_multisearch_fields` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `reid` int(10) unsigned NOT NULL, `type` tinyint(1) unsigned NOT NULL DEFAULT '1', `title` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `idx_reid` (`reid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; EOF; pdo_run($sql);
pdo_exists()
Returns whether a record that meets the criteria exists
explain
boolean pdo_exists($tablename, $condition = array())
parameter
- $tablename = table name
- $condition - conditions met
Examples
//Whether there is a service number, corresponding to sql:SELECT * FROM `ims_account` WHERE `type` = 4 LIMIT 1 var_dump(pdo_exists('account', array('type' => ACCOUNT_SERVICE_VERIFY)));
pdo_fieldexists()
Check if a field exists in the table
explain
boolean pdo_fieldexists($tablename, $fieldname)
parameter
- The $tablename} parameter specifies the name of the table to check
- The $fieldname parameter specifies the field name to check for existence
Examples
//If shopping_ If the credit field does not exist in the goods table, a new credit field is added if(!pdo_fieldexists('shopping_goods', 'credit')) { pdo_query("ALTER TABLE ".tablename('shopping_goods')." ADD `credit` int(11) NOT NULL DEFAULT '0';"); }
pdo_indexexists()
Check if an index exists in the table
explain
boolean pdo_indexexists($tablename, $indexname)
parameter
- The $tablename # parameter specifies the name of the table to check
- The $indexname} parameter specifies the index name to check for existence
Examples
//If site_ If the multiid index does not exist in the slide table, the multiid index is added if (!pdo_indexexists('site_slide', 'multiid')) { pdo_query("ALTER TABLE ".tablename('site_slide')." ADD INDEX `multiid` (`multiid`);"); }
pdo_tableexists()
Check whether a table exists in the database
explain
boolean pdo_tableexists($tablename)
parameter
- The $tablename} parameter specifies the name of the table to check
Examples
if (!pdo_tableexists('site_slide')) { echo 'Table does not exist'; }
pdo_fieldmatch()
Check whether the field types in a table match
explain
boolean pdo_fieldmatch($tablename, $fieldname, $datatype = '', $length = '')
parameter
- $tablename - name of the table to check
- $fieldname - name of the field to be detected
- $datatype - checks whether the field matches this value
- $length checks whether the length of the field matches this value
Examples
pdo_fieldmatch('users', 'uid', 'varchar'); // If the type does not match, return - 1 pdo_fieldmatch('users', 'uid', 'int'); // If the type matches, return true pdo_fieldmatch('users', 'uid', 'int', 5); // If the length does not match, return - 1
pdo_insertid()
Get the ID generated by the previous INSERT operation
explain
int pdo_insertid()
parameter
nothing
Examples
pdo_insert('uni_account', array('name' => 'test', 'description' => 'test')); $result = pdo_insertid();
pdo_fetchallfields()
Get all field names
explain
array pdo_fetchallfields($tablename)
parameter
- $tablename = table name
Examples
var_dump(pdo_fetchallfields('ims_account'));
pdo_debug()
Debug and run SQL statements to display the stack of executed SQL
explain
array pdo_debug($output = true, $append = array())
parameter
- $output - do you want to output execution records and execution error messages
- $append - add execution information. If this parameter is not empty, the $output parameter is false
Examples
pdo_debug(); //The result of calling this function is as follows Array ( [0] => Array ( [sql] => SET NAMES 'utf8'; [error] => Array ( [0] => 00000 [1] => [2] => ) ) [1] => Array ( [sql] => SELECT `value` FROM `ims_core_cache` WHERE `key`=:key [params] => Array ( [:key] => setting ) [error] => Array ( [0] => 00000 [1] => [2] => ) ) )
Overview of chained queries
The chain query class provides an object-oriented way to query data. The chain query only supports some common simple queries and complex business requirements. It is recommended to use SQL statements directly.
Query the first ten ordinary user data in the user table, and the code is as follows:
$query = load()->object('query'); $row = $query->from('users')->where('type', '1')->orderby('uid', 'desc')->limit(10)->getall();
In the above code, from, where, orderby and limit are called chained calls. Except that you must first specify which table from() and finally call * * get() * * and * * getall() * * when you need to obtain data, the writing of other functions does not distinguish the order.
However, it is not recommended to directly instantiate the Query object for data Query. For programmers, the following code is not much different from the above in "semantics". Chain Query only simplifies and facilitates the writing of SQL statements. We can know what data he is querying by looking at the code, but we don't know the significance and function of doing so.
pdo_fetchall("SELECT * FROM `users` WHERE type = '1' ORDER BY id DESC LIMIT 10");
Therefore, we prefer to combine the Query class with the Table class. For example, the above Query can be transformed into:
class UsersTable extends We7Table { public function searchNewUserList() { return $this->query->from('users')->getall(); } public function searchWithType($type) { $this->where('type', $type); return $this; } public function searchCount($limit) { $this->limit($limit); return $this; } } $usertable = new UsersTable(); $usertable->searchWithType(1); $usertable->searchCount(10); $list = $usertable->searchNewUserlist();
The above code can clearly understand the intention of the inquirer, and can be modified flexibly. For example, if the business changes, you only need to query the latest 20 ordinary users
$usertable->searchCount(20);
Just.
In the micro engine, all Query objects exist in the form of Table objects, stored in the Framework/table directory, and called in the following ways:
$users_table = table('users'); $users_table->searchWithFounder(ACCOUNT_MANAGE_GROUP_VICE_FOUNDER); $users_table->searchWithPage($pindex, $psize); $users = $users_table->getUsersList();
from()
explain
Query from($tablename, $alias = '')
Specify the table name to query
parameter
- The $tablename # parameter specifies the name of the data table to be queried. Do not use the tablename() function for the table name passed in here
- $alias} table alias, which is convenient to use when constructing conditional statements and associations
Examples
//If you specify an alias, you can use it later Field name $query = load()->object('query'); $row = $query->from('users', 'u')->select('u.username')->get();
select()
explain
Query select($field1, $field2, ...)
Specify the field list to query, which is equivalent to SELECT *, SELECT name and username
parameter
- $field specifies the field name to query, which can be multiple parameters or an array
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->select('uid', 'username')->get(); //You can also pass in an array $row = $query->from('users', 'u')->select(array('uid', 'username'))->get();
where()
explain
Query where(array | string $condition, $parameters = array())
Specify query criteria. If multiple criteria can be connected to multiple where functions or $condition is specified as an array, all query criteria will be connected with AND
parameter
- $condition specifies the condition field to query, and also supports range condition operations, '>', '<', '< >', '! =', '> =', '< =', '+ =', '- ='‘ LIKE’, ‘like’
- $parameters - specifies the value of the query criteria
Examples
//The alias is specified in the users table, and the alias prefix can be written in the subsequent fields if necessary $query = load()->object('query'); $row = $query->from('users', 'u')->where('u.type', '1')->where('uid >=', '2')->get(); //Conditions can also be written together $row = $query->from('users', 'u')->where(array('u.type' => 1, 'uid >=' => 2))->get();
whereor()
explain
Query whereor(string | array $condition, $parameters = array())
It is the same as where, except that this function is connected by OR
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->where('type', '1')->whereor('uid', 2)->get(); //Generate SQL as follows SELECT * FROM users AS U WHERE type = '1' OR uid = '2' LIMIT 1
having()
explain
Query having(string | array $condition, $parameters = array())
Specify the conditions to query. The same as the where parameter and the use method, different having is executed after the aggregate function. It is generally used together with groupby
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->having('count(*) >', 2)->groupby('type')->getall();
groupby()
explain
Query groupby($field)
Specify the fields to group
parameter
- $field - name of the field to be grouped
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->groupby('u.type')->get();
orderby()
explain
Query orderby($field, $direction = 'ASC')
Specify the fields and how query results are sorted
parameter
- $field - name of field to sort
- $direction - sorting method, which can be ASC or DESC
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->orderby('u.uid', 'DESC')->get();
leftjoin()
explain
Query leftjoin($tablename, $alias = '')
Specify the table to be left associated. When rightjoin is required, please change the writing order
parameter
- The $tablename # parameter specifies the name of the data table to be queried. Do not use the tablename() function for the table name passed in here
- $alias} table alias, which is convenient to use when constructing conditional statements and associations
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->leftjoin('users_profile', 'b')->on('u.uid', 'b.uid')->where('u.uid', '1')->get(); //If there are multiple association conditions, use array form on(array('u.uid' => 'b.uid', 'u.username' => 'b.realname'))
innerjoin()
explain
Query innerjoin($tablename, $alias = '')
Use the same method as leftjoin
on()
explain
Query on($condition, $parameters = array())
Specify the Association criteria in the association query
parameter
Like the where function, multiple association conditions can be in the form of an array, and only one on statement can appear in an association query
limit()
explain
Query limit(start, size)
Specify the number of rows from which to query, which is the same as the meaning of Limit in SQL statement
parameter
- $start - what line does the query start from
- $size how many rows to query
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->limit(1, 10)->getall();
page()
explain
Query page(pageindex, pagesize)
Get the data according to the page, and convert it into a limit statement to LIMIT (pageindex - 1) * pagesize, pagesize
parameter
- $pageindex - current page number
- $pagesize - how many pieces of data per page
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->page(1, 10)->getall();
get()
explain
array get()
Get a record
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->get();
getall()
explain
array getall($keyfield = '')
Get all records
parameter
- $keyfield: gets the field specified as the key value of the recordset array. The default is natural sorting
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->limit(1, 10)->getall('uid');
getcolumn()
explain
Mixed getcolumn($field = '')
Gets the value of the specified field in a record
parameter
- $field - which field value to obtain
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->getcolumn('username');
count()
explain
int count()
How many result sets are obtained only
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->count();
exists()
explain
boolean exists()
Gets whether data that meets a condition exists
Examples
$query = load()->object('query'); $is_found = $query->from('users', 'u')->where('uid', 10)->exists();
getLastQueryTotal()
explain
int getLastQueryTotal()
When the limit restriction statement is used in the query, the function can be called to get the data of the whole table after completing the query, which is usually used for paging.
Examples
$pindex = max(1, intval($_GPC['page'])); $psize = 20; $query = load()->object('query'); $row = $query->from('users', 'u')->page($pindex, $psize)->getall(); $total = $query->getLastQueryTotal(); $pager = pagination($total, $pindex, $psize); //Page HTML
getLastQuery()
explain
array getLastQuery()
Get the last executed SQL statement and parameters, which are mainly used for debugging code
Examples
$query = load()->object('query'); $row = $query->from('users', 'u')->get(); print_r($query->getLastQuery());