For the introduction of database abstraction layer and database connection, please refer to: PDO introduction of php database abstraction layer and simple example: php uses the PDO abstraction layer to obtain query results. There are three main methods: (1) PDO: query () query. See the following section of php
For the introduction of database abstraction layer and database connection, see: PDO introduction and simple examples of php database abstraction layer
Php uses the PDO abstraction layer to obtain query results. There are three methods:
(1) PDO: query () query.
See the following php code:
Query ('select * from user'); $ res-> setFetchMode (PDO: FETCH_NUM); // while ($ row = $ res-> fetch ()) {print_r ($ row) ;}?>
(2) PDO-> exec () processing SQL
Exec () processes SQL $ db-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); $ res = $ db-> exec ("insert into user (id, name) values ('', 'php point pass')"); echo $ res;?>
(3) PDO: prepare () preprocessing query
Prepare ("select * from user"); $ res-> execute (); while ($ row = $ res-> fetchAll ()) {print_r ($ row) ;}?>
The setAttribute () method is to set Attributes. common parameters are as follows:
PDO: CASE_LOWER -- force column name to be lowercase
PDO: CASE_NATURAL -- column names follow the original method
PDO: CASE_UPPER -- force column name to uppercase
The setFetchMode method is used to set the type of the return value for the result set. common parameters are as follows:
PDO: FETCH_ASSOC -- join array form
PDO: FETCH_NUM -- numeric index array format
PDO: FETCH_BOTH -- both arrays are available, which is the default
PDO: FETCH_OBJ -- according to the object form, similar to the previous mysql_fetch_object ()
The above is summarized as follows:
Query operations are mainly PDO: query (), PDO: exec (), PDO: prepare ().
PDO-> query ()-processes an SQL statement and returns a "PDOStatement"
PDO-> exec ()-processes an SQL statement and returns the number of affected items
PDO: prepare () is mainly used for preprocessing. you need to use $ rs-> execute () to execute the SQL statement in the preprocessing.
Finally, we will introduce two common functions:
(1) fetchColumn () is used to obtain the result of a field in the specified record. the default value is the first field!
Query ('select * from user'); // obtain the result of the second field in the specified record $ col = $ res-> fetchColumn (1); echo $ col;?>
(2) fetchAll (), which obtains data from a result set and stores the data in the associated array.
query('select * from user');$res_arr =$res->fetchAll();print_r($res_arr);?>
The php Tutorial later will introduce in detail the PDO preprocessing query, and provide powerful functions!