


PHP uses pdo to connect to the access database and display data operations in a loop
Jun 05, 2018 pm 04:38 PMThis article mainly introduces the operation of PHP using pdo to connect to the access database and display the data in a loop. It analyzes in detail the operation skills and related operations of PHP using pdo to connect to the access database, query, execute sql statements, preprocessing, etc. in the form of examples. Notes, friends in need can refer to
This article describes the example of PHP using pdo to connect to the access database and display the data in a loop. Share it with everyone for your reference, the details are as follows:
PDO connection and query:
try { $conn = new PDO("odbc:driver={microsoft access driver (*.mdb)}; dbq=".realpath("MyDatabase.mdb")) or die("鏈接錯誤!"); //echo "鏈接成功!"; } catch(PDOException $e){ echo $e->getMessage(); } $sql = "select * from users";
1. foreach()
Method
foreach ($conn->query($sql) as $row) { $row["UserID"]; $row["UserName"]; $row["UserPassword"]; }
2. while()
Method
$rs = $conn->query($sql); $rs->setFetchMode(PDO::FETCH_NUM); while($row=$rs->fetch()){ $row[0]; $row[1]; $row[2]; }
php uses the PDO abstraction layer to obtain query results. There are three main ways:
(1) PDO::query()
Query.
Look at the following php code:
<?php //PDO::query()查詢 $res = $db->query('select * from user'); $res->setFetchMode(PDO::FETCH_NUM); //數(shù)字索引方式 while ($row = $res->fetch()){ print_r($row); } ?>
(2)PDO->exec()
Processing sql
<?php //PDO->exec()處理sql $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $res = $db->exec("insert into user(id,name) values('','php點點通')"); echo $res; ?>
(3)PDO::prepare()
Preprocessing execution query
<?php //PDO::prepare()預(yù)處理執(zhí)行查詢 $res = $db->prepare("select * from user"); $res->execute(); while ($row = $res->fetchAll()) { print_r($row); } ?>
setAttribute()
The method is to set attributes. Common parameters are as follows:
PDO::CASE_LOWER -- Force column names to be lowercase
PDO::CASE_NATURAL -- Column names are in original form
PDO::CASE_UPPER -- Force column names to be uppercase
setFetchMode
Method to set the type of return value for obtaining the result set. Common parameters are as follows:
PDO::FETCH_ASSOC -- Associative array form
PDO::FETCH_NUM -- Numeric index array form
PDO::FETCH_BOTH -- Both array forms are available, this is the default
PDO::FETCH_OBJ -- Follow The form of the object is similar to the previous mysql_fetch_object()
The above is summarized as follows:
The query operation is mainly PDO::query()
, PDO: :exec()
, PDO::prepare()
.
PDO->query() — Process a SQL statement and return a "PDOStatement"
PDO->exec() — Process a SQL statement, and returns the number of affected entriesPDO::prepare()
Mainly a preprocessing operation, you need to execute the SQL statement in the preprocessing through $rs->execute()
Finally, two commonly used functions are introduced:
(1)fetchColumn()
Get the result of a field in the specified record, the default is the first one Field!
<?php $res = $db->query('select * from user'); //獲取指定記錄里第二個字段結(jié)果 $col = $res->fetchColumn(1); echo $col; ?>
(2)fetchAll()
, get data from a result set, and then store it in an associative array
<?php $res = $db->query('select * from user'); $res_arr =$res->fetchAll(); print_r($res_arr); ?>
Related recommendations:
PHP ADODB generates HTML table function rs2html function [with error handling function usage]
Example of PHP using regular expressions to filter illegal strings
# #
The above is the detailed content of PHP uses pdo to connect to the access database and display data operations in a loop. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

The key to writing PHP comments is clear, useful and concise. 1. Comments should explain the intention behind the code rather than just describing the code itself, such as explaining the logical purpose of complex conditional judgments; 2. Add comments to key scenarios such as magic values, old code compatibility, API interfaces, etc. to improve readability; 3. Avoid duplicate code content, keep it concise and specific, and use standard formats such as PHPDoc; 4. Comments should be updated synchronously with the code to ensure accuracy. Good comments should be thought from the perspective of others, reduce the cost of understanding, and become a code understanding navigation device.

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.
