search
HomeBackend DevelopmentPHP TutorialPHP understands the PDO database abstraction layer, phppdo database abstraction_PHP tutorial

PHP understands the PDO database abstraction layer, phppdo database abstraction

The full name of PDO is PHP Data Object (PHP Data Object), which is an extension of PHP connection database. Currently Be commonly used. The main problem solved by PDO is to provide a unified data access interface and operation layer for different databases. It provides a better solution for the development and migration of the system across database platforms. Acquisition of PDO objects
In PDO, to establish a connection with the database, you need to instantiate the constructor of PDO. The PDO constructor syntax is as follows:
PDO::__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
Connect to the database through the PDO constructor:

<span> 1</span> <?<span>php
</span><span> 2</span> <span>$dbms</span> = 'mysql'<span>;
</span><span> 3</span> <span>$dbName</span> = 'dormitory'<span>;
</span><span> 4</span> <span>$host</span> = 'localhost'<span>;
</span><span> 5</span> <span>$user</span> = 'root'<span>;
</span><span> 6</span> <span>$pwd</span> = ''<span>;
</span><span> 7</span> <span>$dsn</span> = "<span>$dbms</span>:host=<span>$host</span>;dbname=<span>$dbName</span>"<span>;
</span><span> 8</span> <span>try</span><span> {
</span><span> 9</span>     <span>$pdo</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$pwd</span><span>);
</span><span>10</span>     <span>echo</span> '连接成功!'<span>;
</span><span>11</span> } <span>catch</span> (<span>Exception</span> <span>$e</span><span>) {
</span><span>12</span>     <span>echo</span> <span>$e</span>->getMessage() . "<br>"<span>;
</span><span>13</span> <span>}
</span><span>14</span> ?>

3 ways to execute sql statements
The methods to execute sql statements are: exec(), query(), prepare()+execute().
1. The exec() method is used to execute input, delete, and update statements, and the return value is the number of affected rows;
2. The query() method is used When executing a select statement, the return value is a two-digit array;
3. The preprocessing statement prepare()+execute() can be used to execute input, delete, update, and select statements,
You can think of prepared statements as a compiled template of the SQL you want to run. It can be customized using variable parameters, so that it only needs to be parsed once when querying. Can be executed multiple times;
If the application only uses prepared statements, it can ensure that SQL injection will not occur.
PDO::prepare() returns a PDOStatement object, and the content of the object is the parameters in the prepare() method;
PDO::execute(), Check whether sql is executable, and the return value is a boolean type.
It can also be seen from the return value of the prepared statement that he does not actually execute the sql statement, but checks the correctness of the sql, prepares the execution status, and waits until the result set is needed and then execute it.

<span> 1</span> <?<span>php
</span><span> 2</span>             <span>include_once</span> './pdo_db_conn.php'<span>;
</span><span> 3</span>             <span>try</span><span> {
</span><span> 4</span>                 <span>$query</span> = "select * from building"<span>;
</span><span> 5</span> <span>//</span><span>                $result = $pdo->query($query);//结果为一个二维数组</span>
<span> 6</span>                 <span>$result</span> = <span>$pdo</span>->prepare(<span>$query</span><span>);
</span><span> 7</span>                 <span>var_dump</span>(<span>$result</span><span>);
</span><span> 8</span>                 <span>$flag</span> = <span>$result</span>-><span>execute();
</span><span> 9</span>                 <span>var_dump</span>(<span>$flag</span><span>);
</span><span>10</span>             } <span>catch</span> (<span>Exception</span> <span>$e</span><span>) {
</span><span>11</span>                 <span>echo</span> <span>$e</span>-><span>getMessage();
</span><span>12</span> <span>            }
</span><span>13</span>             ?>

Return value:

object(PDOStatement)[2]
public 'queryString' => string 'select * from building' (length=22)

boolean true

3 ways to get the result set
The methods to get the result set are fetch(), fetchAll(), fetchColumn();
The fetch() method gets the next row in the result set, which is an array;
fetchAll() method gets all the rows in the result set, which is an array;
The fetchColumn() method gets the value of the column specified in the next row in the result set.
The calling object type of the three methods is the PDOStatement object type, which is usually executed after the prepared statement.

3 methods to capture sql statements Error method in
When an error occurs when executing a sql statement, the method of displaying the error can be determined according to the set error prompt method.
Error prompt methods are:
1. PDO::ERRMODE_SILENT
Default mode, when an error occurs, the program continues to execute without error hint.
2. PDO::ERRMODE_WARNING
Execution will continue when an error occurs, and a warning message will be prompted for the wrong part.
3. PDO::ERRMODE_EXCEPTION
Execution will not continue when an error occurs, and an exception message will be prompted for the wrong part.

2 ways to get program error information
When an error occurs when executing a sql statement (access to the database part, the result set Traversal errors will not be prompted), can output error information in the background through the errorCode() and errorInfo() methods. When the sql statement is executed through precompilation, these two methods are not applicable. When the errorCode() method is called in the program and the return value is 00000 (5 zeros), it means there is no error in the program, but when the other 5 characters are returned, it means there is an error in the program, At this time, you can view specific error information by calling the errorInfo() method.

PDO module in PHP

This has a little to do with the PHP version. For example, PHP5.2 needs to open both php_pdo.dll and php_pdo_mysql.dll, while php5.4 only needs to open php_pdo_mysql.dll

How to operate database with php pdo

$s_sql = select username,password from t_table where username=? and password=?;
$sth = $dbh->prepare($s_sql);
$result = $sth->execute (array($username,$password));
$result = $sth->fetchAll();//If it does not exist, an empty array is returned. If it exists, it is the username + password

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/892526.htmlTechArticlePHP Understand the PDO database abstraction layer, phppdo database abstraction. The full name of PDO is PHP Data Object (PHP data object), which is PHP An extension in connection databases that is now in common use. PDO Master...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use