Home > Article > Backend Development > Parsing the PDO::fetch() method in PHP
It is often necessary to query data in the database in PHP. PDO is the more mainstream connection method now. PDO::fetch()
is the main method of querying data in PDO. This article will take you through Let’s take a look at how to use the fetch()
method.
First let’s take a look at the syntax of the fetch()
method:
fetch ( int $fetch_style = ? , int $cursor_orientation = PDO::FETCH_ORI_NEXT , int $cursor_offset = 0)
$fetch_style: controls how the next line is returned to the caller
$ursor_orientation: For a scrollable cursor represented by a PDOStatement object, this value determines which row will be returned to the caller.
$offset: For a $cursor_orientation parameter setting, if it is PDO::FETCH_ORI_REL, get the position of the row relative to the cursor before calling PDOStatement::fetch(); if it is PDO:: FETCH_ORI_ABS, specifies the absolute row number of the row you want to get in the result set.
The value returned when this method succeeds depends on the extraction type. In all cases, failure returns false.
Code Example
1. Connect to the database
<?php $servername="localhost"; $username="root"; $password="root123456"; $dbname="my_database"; $pdo=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password); echo "连接成功"."<br>"; $pdo->setAttribute(PDO::ATTR_CASE,PDO::CASE_UPPER); $sql="select * from fate"; $statement=$pdo->prepare($sql); $statement->execute();
2. Several modes of $fetch_style
// PDO::FETCH_ASSOC $result=$statement->fetch(PDO::FETCH_ASSOC); print_r($result); echo "<br>"; // PDO::FETCH_NUM $result=$statement->fetch(PDO::FETCH_NUM); print_r($result); echo "<br>"; // PDO::FETCH_BOTH $result=$statement->fetch(PDO::FETCH_BOTH); print_r($result); echo "<br>"; // PDO::LAZY $result=$statement->fetch(PDO::FETCH_LAZY); print_r($result); echo "<br>"; // PDO::OBJ $result=$statement->fetch(PDO::FETCH_OBJ); print_r($result);
输出:连接成功 Array ([ID] => 1[NAME] => saber[AGE] => 100) Array ([0] => 2[1] => acher[2] => 77) Array ([ID] => 3[0] => 3[NAME] => luncher[1] => luncher [AGE] => 56[2] => 56) PDORow Object ([queryString] => select * from fate[ID] => 4[NAME] => cooker[AGE] => 18) stdClass Object ([ID] => 5[NAME] => 张三[AGE] => 66)
Recommended: 《2021 Summary of PHP interview questions (collection)》《php video tutorial》
The above is the detailed content of Parsing the PDO::fetch() method in PHP. For more information, please follow other related articles on the PHP Chinese website!