PHP PDO get the result set

php using PDO abstraction layer to obtain results, there are three main ways:
(1) PDO :: Query () query.
Look at the following piece of php code:
<? Php // PDO :: Query () query
$ RES = $ db-> Query ( 'the SELECT * from the User');
$ RES-> setFetchMode (PDO :: FETCH_NUM); // digital indexing
the while ($ Row = $ RES-> FETCH ()) {
print_r ($ Row);
}
?>
(2) PDO-> Exec () process SQL
<PHP PDO-//> Exec () process sql?
db- $> the setAttribute (:: ATTR_ERRMODE the PDO, the PDO :: ERRMODE_EXCEPTION);
$ RES = $ db-> Exec ( "INSERT INTO User (ID, name) values ( '', 'little pass PHP')");
echo RES $;
?>
(3) PDO :: PREPARE () pre-execute the query
<php // PDO :: prepare () pre-execute the query?
$ RES = $ db-> PREPARE ( "the SELECT * from the User");
RES- $> Execute ();
the while ($ Row = $ RES->


?>
SetAttribute () method is to set the property, commonly used parameters are as follows:
PDO :: CASE_LOWER - mandatory column name is lowercase
PDO :: CASE_NATURAL - column names in the original way
PDO :: CASE_UPPER - mandatory column called capital
setFetchMode method type set to obtain the results set return value, the following common parameters:
the PDO :: FETCH_ASSOC - associative array form PDO :: FETCH_NUM - numerically indexed array of PDO :: FETCH_BOTH - both have the form of an array, which is the default the PDO :: FETCH_OBJ - in the form of an object, similar to the previous mysql_fetch_object () of the above-summarized as follows: query operations mainly PDO :: query (), PDO :: exec (), PDO :: prepare (). PDO-> query () - processing a SQL statement , and returns a "the PDOStatement" PDO-> Exec () - processing a SQL statement number of entries, and returns the affected PDO :: prepare () pre-processing operation is mainly required by $ rs-> execute () to perform pre-processing inside the SQL statement Finally, two commonly used functions: (1) fetchColumn () Gets the specified record fields in a result, the default is the first field! <? php 











RES = $ db- $> Query ( 'SELECT * from User');
// Get the specified results recorded in the second field
$ = $ RES- COL> fetchColumn (. 1);
echo $ COL;
?>
(2) the fetchAll (), the result obtained from a centralized data, and then stored in an associative array in
<PHP?
Query ( 'SELECT * from User') RES = $ $ db->;
$ $ RES- res_arr => the fetchAll ();
print_r ($ res_arr);
?>

 

I. INTRODUCTION PDO get the result set, had to introduce the PDO if execute SQL statements, in three under normal circumstances,

1.query () method

   query () method is generally used to return the results of the query set. The syntax is: PDOStatement PDO :: Query (String  SQL);

   It is easy to understand the parameters sql, sql statement is to be executed.

2.prepare () method and execute () method

   prepare () method is one of the prepared statement, ready to do the work normally query, and then, execute () to execute the query.

More than a brief introduction of these three cases.

Two, PDO how to get the result set

   pdo obtain the result set, there are three methods, namely fetch (), fetchAll () and fetchColumn () method.

 First of all, you first build a table in a database, named t_user.

 

   CREATE TABLE `t_user` (
   `userid` int(11) NOT NULL,
   `username` varchar(25) DEFAULT NULL,
   `usersex` varchar(6) DEFAULT NULL,
  `userage` int(6) DEFAULT NULL,
   PRIMARY KEY (`userid`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  Then, insert the data, it is very simple, as follows:  

 INSERT INTO `t_user` VALUES ('1', 'li', 'boy', '23');
 INSERT INTO `t_user` VALUES ('2', 'nadia', 'gril', '20');
 INSERT INTO `t_user` VALUES ('3', 'wang', 'boy', '55');

 Here's a brief look at how each method is used.

 

   1.fetch () method

      fecth () is to get the next row of the result set.

      Table I: fetch_style control result set returned alternative embodiment of the value

      

PDO::FETCH_ASSOC Associative array form.
PDO::FETCH_NUM Digital index array.
PDO::FETCH_BOTH Both have an array, which is the default.
PDO::FETCH_OBJ In the form of objects, similar to the previous mysql_fetch_object () function.
PDO::FETCH_BOUND It returns the result as a Boolean value, and the acquired column value is assigned to bindParam () method specified in the variable.
PDO::FETCH_LAZY Digital objects indexed array and returns the result in three forms associative array.

    Specific code ftech () method is as follows:

    

   <Table border = '. 1'>
    <PHP?       $ = DBMS 'mysql'; // select mysql database       $ host = '127.0.0.1'; // hostname database       $ dbName = 'dbtext'; // database use       $ user = ""; // database user name       $ pwd = ""; // database connection password       $ DSN = "$ DBMS: = $ Host Host; dbName dbname = $";       the try {         $ the PDO PDO new new = ($ DSN , $ user, $ pwd); // initialize a PDO object, create a database connection object PDO $         $ Query = "the SELECT * from t_user";         $ $ PDO-the Result => PREPARE ($ Query);         $ result-> the Execute ( );         ? the while ($ RES = $ result-> FETCH (:: FETCH_ASSOC the PDO)) {>       <TR>       <TD> <PHP RES echo $ [ 'the userid'];??> </ TD>       <TD> <?php echo $res['username'];?></td>      <td><?php echo $res['userage'];?></td> 
















      <td><?php echo $res['usersex'];?></td>
      </tr>
    <?php }
    }catch (Exception $e){
    die("error!!!".$e->getMessage()."<br>");
    }
    ?>
  </table>

   The results shown in Figure 1:

   

                                  figure 1

  2.fetchAll () method

     From the word can see very clearly, fetchAll () method is to get all the rows in the result set.

fetch () method

The next line fetch () method for obtaining the result set, the following syntax:

mixed PDOStatement::fetch([int fetch_style][,int cursor_orientation[,int cursor_offset]]])

Return result sets control parameters manner fetch_style

PDO :: FETCH_ASSOC - associative array form
PDO :: FETCH_NUM - numerically indexed array of
PDO :: FETCH_BOTH - both have an array, which is the default
PDO :: FETCH_OBJ - in the form of an object, similar to previous mysql_fetch_object ()
form PDO :: FETCH_BOUND-- returns a Boolean result, while the column values assigned to bindParam acquired (specified variable method).
PDO :: FETCH_LAZY-- return results in an associative array, the array index numbers and forms the object 3

cursor_orientation: PDOStatement objects of a scroll cursor can be used to obtain a specified line.
cursor_offset: offset Cursor

E.g:

Performed by PDO prepared statements prepare () and execute () SQL query, and the application while () statements and fetch () method to complete the data cycle output

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$dbms = 'mysql' ; //数据库类型
$dbName = 'admin' ; //使用的数据库
$user = 'root' ; //数据库连接用户名
$pwd = 'password' ; //数据库连接密码
$host = 'localhost' ; //数据库主机名
$dsn = "$dbms:host=$host;port=3306;dbname=$dbName" ;
try {
$pdo = new PDO( $dsn , $user , $pwd ); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$query = "select * from user" ; //需要执行的sql语句
$res = $pdo ->prepare( $query ); //准备查询语句
$res ->execute();
while ( $result = $res ->fetch(PDO::FETCH_ASSOC)){
echo $result [ 'id' ]. " " . $result [ 'username' ]. " " . $result [ 'password' ]. '<br>' ;
}
} catch (Exception $e ){
die ( "Error!:" . $e ->getMessage(). '<br>' );
}

Operating results as follows:

?
1
2
3
1 107lab e10adc3949ba59abbe56e057f20f883e
4 admin 123456
5 admin 123456

fetchAll () method

the fetchAll () method used to obtain all the rows of the result set, the return value is a result set comprising a binary array of all data. The syntax is as follows:

array PDOStatement::fetchAll([int fetch_style[,int column_index]])

Parameter Description:

fetch_style: centralized control result data is displayed.
column_index: index fields.

E.g:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$dbms = 'mysql' ; //数据库类型
$dbName = 'admin' ; //使用的数据库
$user = 'root' ; //数据库连接用户名
$pwd = 'password' ; //数据库连接密码
$host = 'localhost' ; //数据库主机名
$dsn = "$dbms:host=$host;port=3306;dbname=$dbName" ;
try {
$pdo = new PDO( $dsn , $user , $pwd ); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$query = "select * from user" ; //需要执行的sql语句
$res = $pdo ->prepare( $query ); //准备查询语句
$res ->execute();
$result = $res ->fetchAll(PDO::FETCH_ASSOC);
print_r( $result );
} catch (Exception $e ){
die ( "Error!:" . $e ->getMessage(). '<br>' );
}

Operating results as follows:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Array
(
[0] => Array
(
[id] => 1
[username] => 107lab
[password] => e10adc3949ba59abbe56e057f20f883e
)
[1] => Array
(
[id] => 4
[username] => admin
[password] => 123456
)
[2] => Array
(
[id] => 5
[username] => admin
[password] => 123456
)
)

At this point you can be traversed by the two-dimensional array foreach

?
1
2
3
foreach ( $result as $val ){
echo $val [ 'username' ]. '<br>' ;
}

Operating results as follows:

?
1
2
3
107lab
admin
admin

fetchColumn () method

fetchColumn () method to get the value of the next row in the result set specified column, the following syntax:

string PDOStatement::fetchColumn([int column_number])

Optional parameter index value column_number column line set, from the value zero. If omitted then the value from the first column starts

E.g:

通过fetchColumn()方法获取结果集中下一行中指定列的值。(或第一列id的值)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$dbms = 'mysql' ; //数据库类型
$dbName = 'admin' ; //使用的数据库
$user = 'root' ; //数据库连接用户名
$pwd = 'password' ; //数据库连接密码
$host = 'localhost' ; //数据库主机名
$dsn = "$dbms:host=$host;port=3306;dbname=$dbName" ;
try {
$pdo = new PDO( $dsn , $user , $pwd ); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$query = "select * from user" ; //需要执行的sql语句
$res = $pdo ->prepare( $query ); //准备查询语句
$res ->execute();
echo $res ->fetchColumn(0). '<br>' ;
echo $res ->fetchColumn(0). '<br>' ;
echo $res ->fetchColumn(0). '<br>' ;
} catch (Exception $e ){
die ( "Error!:" . $e ->getMessage(). '<br>' );
}

运行结果为:

?
1
2
3
1
4
5

Guess you like

Origin www.cnblogs.com/yuanscn/p/11237104.html