


Detailed explanation of the fetch() method for obtaining result sets in PDO
When we introduced how PHP operates MYSQL, we also introduced several methods for obtaining result sets. For those who are not familiar with the records, you can go to our special topic PHP Operation MySQL to review. There are also several methods to obtain the result set in PDO. We will introduce these methods one by one!
In the previous article "Three ways to execute SQL statements in PDO", we introduced three ways for PDO to execute SQL statements, so in this article we will introduce PDO acquisition The fetch() method, one of several methods of the result set!
The fetch() method obtains the next row of data in the result set. The specific syntax format of this function is as follows:
mixed PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
Parameter fetch_style: controls the return method of the result set. The optional values are as follows: :
Value | says Ming |
PDO::FETCH_ASSOC | associative array form . |
PDO::FETCH_NUM | Number index array form. |
PDO::FETCH_BOTH | Both are available in array form, which is the default. |
PDO::FETCH_OBJ | In the form of an object, it is similar to the previous mysql_fetch_object() function. |
PDO::FETCH_BOUND | Returns the result in the form of a Boolean value, and assigns the obtained column value to the variable specified in the bindParam() method. |
PDO::FETCH_LAZY | Returns the results in 3 forms: associative array, numeric index array and object. |
Parameter cursor_orientation: A scrolling cursor of the PDOStatement object that can obtain a specified row.
Parameter cursor_offset: The offset of the cursor.
The following example uses the fetch() method to obtain the next row of data in the result set, and then uses the while statement to complete the loop output of the data in the database. The steps are as follows:
First create a php file and use PDO Connect to the MySQL database, then define the SELECT query statement, use the prepare() and execute() methods to perform the query operation, then return the next row of data in the result set through the fetch() method, and set the result set to be returned in the form of an associative array, and finally use the while The statement completes the loop output of the data. The specific code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); //设置页面的编码格式 $dbms = "mysql"; // 数据库的类型 $dbName ="php_cn"; //使用的数据库名称 $user = "root"; //使用的数据库用户名 $pwd = "root"; //使用的数据库密码 $host = "localhost"; //使用的主机名称 $dsn = "$dbms:host=$host;dbname=$dbName"; try{ $pdo=new PDO($dsn,$user,$pwd);//初始化一个PDO对象,就是创建了数据库连接对象$pdo $query="select * from user";//需要执行的sql语句 $res=$pdo->prepare($query);//准备查询语句 $res->execute(); //执行查询语句,并返回结果集 ?> <table border="1" width="500"> <tr> <td height="22" align="center" valign="middle">id</td> <td height="22" align="center" valign="middle">用户名</td> <td height="22" align="center" valign="middle">密码</td> </tr> <?php while($result=$res->fetch(PDO::FETCH_ASSOC)){ // 循环输出查询结果集,并且设置结果集为关联数据形式。 ?> <tr> <td height="22" align="center" valign="middle"><?php echo $result["id"];?></td> <td height="22" align="center" valign="middle"><?php echo $result["username"];?></td> <td height="22" align="center" valign="middle"><?php echo $result["password"];?></td> </tr> <?php } }catch(Exception $e){ die("Error!:".$e->getMessage().'<br>'); } ?> </table>
The final output is as follows:
About the fetch() method of obtaining the result set in PDO, we That’s it for the introduction. You can try it in your local area and contact us to consolidate what you have learned. In the next article, we will continue to introduce to you the method of obtaining the result set in PDO. For details, please read "PDO Detailed explanation of the fetchAll() method to obtain the result set》!
The above is the detailed content of Detailed explanation of the fetch() method for obtaining result sets in PDO. For more information, please follow other related articles on the PHP Chinese website!

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
