Home  >  Article  >  Backend Development  >  PHP implements method of reading data from database table using PDO

PHP implements method of reading data from database table using PDO

墨辰丷
墨辰丷Original
2018-05-22 09:24:221493browse

This article mainly introduces the method of using PDO to read data from the database table in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

After creating the PDO object, you can retrieve data through the created object. To query data, we can use the PDO::query() method. The specific code is as follows:

try{
    $pdo=new PDO('mysql:host=localhost;dbname=alpha','root','password');
}catch(PDOException $e){
    echo "数据库连接失败,原因是:".$e->getMessage();
}

//从数据库中选择数据,并将结果赋予一个变量,testtable为数据库表
$result=$pdo->query('select id,name,age from testtable');

//将查询出的数据输出
while($row=$result->fetch()){
    echo "ID:".$row['id'];
    echo "NAME:".$row['name'];
    echo "AGE:".$row['age'];
}
?>

As can be seen from the above code, we use a while loop Output query results.

Description: The fetch() method will receive a row of data (in the form of an array) from the result set every time it is called, and then execute the while During the loop, the next row of data will be fetched (which can be understood as the pointer automatically moving to the next row of data). If the next row of data exists, it will be fetched. If it does not exist, false will be returned, and the loop ends.

Another method to extract data is: fetchAll(). We can judge its meaning from the name, which is to retrieve all data rows at once.

Note: Both the fetch() and fetchAll() methods accept the fetch_style parameter, which defines how to format the result set.

pdo provides constants for easy use:

PDO::FETCH_ASSOC To complete the above code seen in the while loop, he uses Keygroup returns an array to column names.

For example: print_r($result->fetch(PDO::FETCH_ASSOC));

Output result: Array ([username] => alpha [level] => 1 [ signtime] => )

PDO::FETCH_NUM also returns an array, using numeric keys.

PDO::FETCH_BOTH is the default value. Combined with the above two, it returns the key group and the numeric key. This is also the default method we use most

Related recommendations:

PHP uses PHPExcel to implement batch upload to database

##Discuz!X/Database DB:: Function operation Method

Use ajax to submit the form to the databaseDetailed explanation (no refresh)

The above is the detailed content of PHP implements method of reading data from database table using PDO. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn