Php CodeIgniter Study Notes

Source: Internet
Author: User

Before using the database, we 'd better automatically connect the database: config/autoload. php automatically loads $ autoload ['libraries'] = array ('database ');
Some common functions

Select data
$ This-> db-> select ();
You can write the SELECT part in SQL queries.
$ This-> db-> where ();
$ This-> db-> or_where ();
$ This-> db-> where_in ();
Allow you to write the WHERE part in SQL queries. For more information about other where statements, see the manual.
$ This-> db-> get ();
Run the SELECT query statement and return the result set. You can obtain all the data of a table.
$ This-> db-> like ();
$ This-> db-> or_like ();
$ This-> db-> not_like ();
This function allows you to generate a LIKE clause, which is very useful for queries. For other syntaxes, see the manual.
$ This-> db-> order_by ();
This helps you set an order by clause.
$ This-> db-> group_by ();
You can write the group by section in the query statement:
$ This-> db-> distinct ();
Add the "DISTINCT" keyword to the query statement:
$ This-> db-> having ();
Allows you to write the HAVING section for your query statement.
$ This-> db-> limit ();
Limit the number of results returned by the query:
$ This-> db-> select_max ();
Write a "select max (field)" for your query )".
$ This-> db-> select_min ();
Write a "select min (field)" for your query )".
$ This-> db-> select_avg ();
Write a "select avg (field)" for your query )".
$ This-> db-> select_sum ();
Write a "select sum (field)" for your query )".
$ This-> db-> join ();
You can write the JOIN part in the query.
$ This-> db-> count_all_results ();
You can obtain the number of results returned by a specific Active Record query. You can use the Active Record restriction function, such as where (), or_where (), like (), or_like (), and so on.

Insert data

$ This-> db-> insert ();
Generate an SQL insert string based on the data you provided and execute the query. You can pass an array or an object to a function.
$ This-> db-> insert_batch ();
Insert multiple data records at a time, generate an SQL statement based on the data you provide, insert a string, and execute the query. You can pass an array or an object to a function.
$ This-> db-> set ();
This function enables you to set inserts (insert) or updates (update) values. It can be used instead of directly passing arrays to insert and update functions.

Update Data

$ This-> db-> update ();
Generate and execute an update statement based on the data you provide. You can pass an array or object to this function.
$ This-> db-> update_batch ();
Generates an update string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

Delete data

$ This-> db-> delete ();
Generate and execute a DELETE statement.
$ This-> db-> empty_table ();
Generate and execute a DELETE statement.
$ This-> db-> truncate ();
Generate and execute a TRUNCATE (truncation) statement.

Chain Method

The chained method allows you to simplify your syntax by connecting multiple functions. Consider this example:
$ This-> db-> select ('title')-> from ('mytable')-> where ('id', $ id)-> limit (10, 20 );
$ Query = $ this-> db-> get ();
Note: The chained method can only run under PHP 5.

Query

$ This-> db-> query ();
To submit a query, use the following functions:
$ This-> db-> query ('your query here ');
The query () function returns a database result set in the form of an object. When running a query in "read" mode, you can use "Show your result set" to display the query results. When running a query in "write" mode, TRUE or FALSE will be returned only based on the execution success or failure.

Escape Query

$ This-> db-> escape () is used to determine the data type so that only data of the string type can be escaped. In addition, it will automatically enclose the data in single quotes, so you do not need to manually add single quotes. Usage: $ SQL = "INSERT INTO table (title) VALUES (". $ this-> db-> escape ($ title ). ")";

Query auxiliary functions

$ This-> db-> insert_id ()
This ID is the ID of the data inserted.
$ This-> db-> affected_rows ()
When a query is executed for write operations (insert, update, etc.), the number of affected rows is displayed.
$ This-> db-> count_all ();
Calculates the total number of rows in the specified table and returns the result. Write the committed table name in the first parameter.

Generate query record set

Result ()
If this method is successfully executed, an array of objects is returned. If it fails, an empty array is returned.
Result_array ()
When this method is successfully executed, the record set is returned as an associated array. An empty array is returned when a failure occurs.
Row ()
This function returns the first row of data of the current request as an object.

You can pass parameters (the parameter is the row index) to obtain data of a row. For example, we want to obtain 5th rows of data: $ row = $ query-> row (4 );

Row_array ()
Similar to row (), the function returns an array.

In addition, we can use the following method to retrieve records through a cursor:
$ Row = $ query-> first_row ()
$ Row = $ query-> last_row ()
$ Row = $ query-> next_row ()
$ Row = $ query-> previus_row ()
By default, they will return an object, and you can also pass the parameter "array" to use the array method to obtain data $ row = $ query-> first_row ('array ')
$ Row = $ query-> last_row ('array ')
$ Row = $ query-> next_row ('array ')
$ Row = $ query-> previus_row ('array ')

Auxiliary Functions of result set

$ Query-> num_rows ()
This function returns the number of rows in the current request.
$ Query-> num_fields ()
This function returns the number of fields in the current request (number of columns ):
$ Query-> free_result ()
This function will release the memory occupied by the current query and delete its associated resource IDs.

Automatic Connection

The "Automatic Connection" function will be automatically instantiated when each page is loaded. To enable "Automatic Connection", you can add the database to the library array in application/config/autoload. php:
$ Autoload ['libraries'] = array ('database ');

Manual connection

If only a part of the page requires database connection, you can manually add the following code in the function you need or in your class for this class.
$ This-> load-> database ();

Connect to multiple databases

If you need to connect to more than one database at the same time, you can use the following methods:
$ DB1 = $ this-> load-> database ('group _ one', TRUE );
$ DB2 = $ this-> load-> database ('group _ two', TRUE );

Table Data

$ This-> db-> list_tables ();
Returns an array containing the names of all tables in the currently connected database.
$ This-> db-> table_exists ();
Sometimes, before performing an operation on a table, you can use this function to determine whether a specified table exists. Returns a Boolean value.

Database tools

Note: Before initializing the database tool class, your database driver must be running because the tool class depends on this.
Loading tool class: $ this-> load-> dbutil ()
Once Initialization is complete, you can use the $ this-> dbutil object to access the member function:
$ This-> dbutil-> list_databases ()
$ This-> dbutil-> database_exists ();
$ This-> dbutil-> xml_from_result ($ db_result)
$ This-> dbutil-> backup ()

Database cache

Three steps are required to activate the cache:
1. Create a writable directory on the server to save the cached files.
2. In the application/config/database. php file, set the $ db ['xxxx'] ['cachedir'] Directory.
3. Activate the cache feature in the application/config/database file. set the global option $ db ['xxxx'] ['cache _ on'] = 'true' in php. You can also set it manually using the method below this page.
Once activated, the cache automatically occurs when a page containing database queries is loaded.

When a database is updated, We need to delete the cached files.
$ This-> db-> cache_delete ()
Delete cached files and specific webpages. If you need to clear the cache, update your database
$ This-> db-> cache_delete ('/blog', 'comments ');
Note: $ this-> db-> cache_delete ('blog ', 'comments') is written in the manual '); however, you must add a slash '/' before the Controller name to perform the test.
$ This-> db-> cache_delete_all ()
Clear all cached files.

Database Maintenance

Note: to initialize the database maintenance class, make sure that your database driver is running because the class depends on the database driver.
Use the following method to load the database maintenance class:
$ This-> load-> dbforge ()
Once initialized, you can use the functions in the $ this-> dbforge object functions class:
$ This-> dbforge-> create_database ('db _ name ')
Allows you to create a database specified by the first parameter.
$ This-> dbforge-> drop_database ('db _ name ')
Allows you to delete a database specified by the first parameter.
$ This-> dbforge-> create_table ('table _ name ');
After declaring fields and keys, you can create a table.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.