search
HomeBackend DevelopmentPHP TutorialDetailed explanation of usage of php pdo function library

  1. pdo->begintransaction() — Mark the starting point of rollback
  2. pdo->commit() — Mark the end point of rollback and execute sql
  3. pdo->__construct() — Establish a pdo link database Example of
  4. pdo->errorcode() — Get error code
  5. pdo->errorinfo() — Get error information
  6. pdo->exec() — Process a sql statement and return the number of entries affected
  7. pdo ->getattribute() — Get the attributes of a "database connection object"
  8. pdo->getavailabledrivers() — Get the valid pdo driver name
  9. pdo->lastinsertid() — Get the primary key of the last piece of data written Value
  10. pdo->prepare() — Generate a "query object"
  11. pdo->query() — Process a sql statement and return a "pdostatement"
  12. pdo->quote() — For a certain sql Add quotes to the string
  13. pdo->rollback() — perform rollback
  14. pdo->setattribute() — set attributes for a "database connection object"
Copy code

2. pdostatement

  1. pdostatement->bindcolumn() — bind a column to a php variable
  2. pdostatement->bindparam() — binds a parameter to the specified variable name
  3. pdostatement->bindvalue() — binds a value to a parameter
  4. pdostatement->closecursor() — closes the cursor, enabling the statement to be executed again.
  5. pdostatement->columncount() — returns the number of columns in the result set
  6. pdostatement->errorcode() — fetch the sqlstate associated with the last operation on the statement handle
  7. pdostatement->errorinfo() — fetch extended error information associated with the last operation on the statement handle
  8. pdostatement->execute() — executes a prepared statement
  9. pdostatement ->fetch() — fetches the next row from a result set
  10. pdostatement->fetchall() — returns an array containing all of the result set rows
  11. pdostatement->fetchcolumn() — returns a single column from the next row of a result set
  12. pdostatement->fetchobject() — fetches the next row and returns it as an object.
  13. pdostatement->getattribute() — retrieve a statement attribute
  14. pdostatement->getcolumnmeta() — returns metadata for a column in a result set
  15. pdostatement->nextrowset() — advances to the next rowset in a multi-rowset statement handle
  16. pdostatement->rowcount() — returns the number of rows affected by the last sql statement
  17. pdostatement- >setattribute() — set a statement attribute
  18. pdostatement->setfetchmode() — set the default fetch mode for this statement
Copy code

Detailed explanation 1) Database connection in pdo

  1. $dsn = 'mysql:dbname=ent;host=127.0.0.1′;
  2. $user = 'root';
  3. $password = '123456';
  4. try {
  5. $dbh = new pdo($ dsn, $user, $password, array(pdo::attr_persistent => true));
  6. $dbh->query('set names utf8;');
  7. foreach ($dbh->query('select * from tpm_juese') as $row) {
  8. print_r($row);
  9. }
  10. } catch (pdoexception $e) {
  11. echo 'connection failed: ' . $e->getmessage();
  12. }
Copy code

Many web applications will be optimized by using persistent connections to the database. Persistent connections are not closed at the end of the script, Instead it is cached and reused when another script requests a connection with the same ID. The cache of persistent connections allows you to avoid the resource consumption of deploying a new connection every time the script needs to talk to the database, making your web application faster. The array(pdo::attr_persistent => true) in the above example sets the connection type to a persistent connection.

Detailed explanation 2) Transactions in pdo The three methods pdo->begintransaction(), pdo->commit(), and pdo->rollback() are used together when the rollback function is supported. The pdo->begintransaction() method marks the starting point, the pdo->commit() method marks the rollback end point and executes sql, and pdo->rollback() performs rollback.

  1. try {
  2. $dbh = new pdo('mysql:host=localhost;dbname=test', 'root', ”);
  3. $dbh->query('set names utf8;');
  4. $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception);
  5. $dbh->begintransaction();
  6. $dbh->exec(”insert into `test`.` table` (`name` ,`age`)values ​​('mick', 22);”);
  7. $dbh->exec(”insert into `test`.`table` (`name` ,`age`) values ​​('lily', 29);");
  8. $dbh->exec("insert into `test`.`table` (`name` ,`age`)values ​​('susan', 21);") ;
  9. $dbh->commit();
  10. } catch (exception $e) {
  11. $dbh->rollback();
  12. echo “failed: ” . $e->getmessage();
  13. }
  14. ? >
Copy code

Now that the connection has been established through pdo, you must understand how pdo manages transactions before deploying the query. If you have never encountered transaction processing before, (now a brief introduction. :) They provide 4 main features: atomicity, consistency, isolation and durability (acid). In layman's terms, all the work in a transaction is committed when it is committed, even if it is It is executed in stages and must be applied safely to the database without being interfered by other connections. The transaction work can also be easily canceled automatically when an error occurs in the request.

The typical use of transactions is to "save" batch changes and then execute them immediately. This will have the benefit of completely improving update efficiency. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to realize this benefit).

Unfortunately, not every database supports transactions, so pdo needs to be running in what is considered "autocommit" mode when the connection is established. Autocommit mode means that every query you execute has its own implicit transaction processing, whether the database supports transactions or there is no transaction because the database does not support it. If you need a transaction, you must create one using the pdo->begintransaction() method. If the underlying driver does not support transactions, a pdoexception will be thrown (regardless of your exception handling settings, since this is always a serious error condition). Within a transaction, you can end it using pdo->commit() or pdo->rollback(), depending on whether the code in the transaction ran successfully. When the script ends or a connection is closed, if you have an unfinished transaction, pdo will automatically roll it back. This is a safe solution in case the script terminates unexpectedly - if you don't explicitly commit the transaction, it will assume that something went wrong and perform a rollback for the safety of your data.

2. pdostatement

  1. // Modify the default error display level
  2. $dbh->setattribute(pdo::attr_errmode, pdo::errmode_warning);
  3. ?>
Copy code

Attribute list: pdo::param_bool represents a boolean type pdo::param_null Represents a null type in sql pdo::param_int Represents an integer type in sql pdo::param_str Represents sql char, varchar type in sql pdo::param_lob Represents a large object type in SQL pdo::param_stmt Represents a recordset type in SQL, which is not supported yet. pdo::param_input_output specifies that the parameter is an inout parameter for a stored procedure. you must bitwise-or this value with an explicit pdo::param_* data type. pdo::fetch_lazy Return each row of results as an object pdo::fetch_assoc Only the result set of the query with the key value as the subscript is returned. Only one data with the same name is returned. pdo::fetch_named Only the result set of the query with the key value as the subscript is returned. Data with the same name is returned in the form of an array. pdo::fetch_num Returns only result sets for queries with numbers as subscripts pdo::fetch_both Returns the result set of queries with key values ​​and numbers as subscripts at the same time pdo::fetch_obj Return the result set as an object pdo::fetch_bound Assign the value bound to pdostatement::bindparam() and pdostatement::bindcolumn() as a variable name and return it pdo::fetch_column Indicates that only a certain column in the result set is returned pdo::fetch_class Indicates that the result set is returned in the form of a class pdo::fetch_into Indicates merging data into an existing class for return pdo::fetch_func pdo::fetch_group pdo::fetch_unique pdo::fetch_key_pair Return the result set in the form of a table below the first key value and a table below the following numbers. pdo::fetch_classtype pdo::fetch_serialize Indicates merging data into an existing class and serializing it back pdo::fetch_props_late available since php 5.2.0 pdo::attr_autocommit When set to true, pdo will automatically try to stop accepting commissions and start executing pdo::attr_prefetch Set the data size that the application obtains in advance. Not all databases support it. pdo::attr_timeout Set the value of database connection timeout pdo::attr_errmode Set error handling mode pdo::attr_server_version Read-only attribute indicating the server-side database version of the pdo connection pdo::attr_client_version Read-only attribute, indicating the client pdo driver version of the pdo connection pdo::attr_server_info Read-only attribute, indicating the meta information of the server to which pdo is connected pdo::attr_connection_status pdo::attr_case Operate the column form through the contents in pdo::case_* pdo::attr_cursor_name Get or set the name of the pointer pdo::attr_cursor Set the type of pointer, pdo now supports pdo::cursor_fwonly and pdo::cursor_fwonly pdo::attr_driver_name Returns the name of the pdo driver used pdo::attr_oracle_nulls Convert the returned empty string to sql's null pdo::attr_persistent Get an existing connection pdo::attr_statement_class pdo::attr_fetch_catalog_names In the returned result set, use custom catalog names in place of field names. pdo::attr_fetch_table_names In the returned result set, use custom table names in place of field names. pdo::attr_stringify_fetches pdo::attr_max_column_len pdo::attr_default_fetch_mode available since php 5.2.0 pdo::attr_emulate_prepares available since php 5.1.3. pdo::errmode_silent No error message is reported when an error occurs, which is the default value. pdo::errmode_warning Send a php e_warning message when an error occurs pdo::errmode_exception Throws a pdoexception when an error occurs pdo::case_natural Default display format for reply columns pdo::case_lower Force column names to be lowercase pdo::case_upper Force column names to be capitalized pdo::null_natural pdo::null_empty_string pdo::null_to_string pdo::fetch_ori_next Get the next row of data in the result set, only valid when using pointer function pdo::fetch_ori_prior Get the previous row of data in the result set. It is only valid when there is a pointer function. pdo::fetch_ori_first Get the first row of data in the result set, only valid when there is a pointer function pdo::fetch_ori_last Get the last row of data in the result set, only valid when using pointer function pdo::fetch_ori_abs Get a certain row of data in the result set, only valid when there is a pointer function pdo::fetch_ori_rel Get the data of a row after the current row in the result set. It is only valid when there is a pointer function. pdo::cursor_fwonly Create a backward-only pointer operation object pdo::cursor_scroll Create a pointer operation object and pass the contents in pdo::fetch_ori_* to control the result set pdo::err_none (string)

Set the error message when there is no error pdo::param_evt_alloc allocation event pdo::param_evt_free deallocation event pdo::param_evt_exec_pre event triggered prior to execution of a prepared statement. pdo::param_evt_exec_post event subsequently triggered to execution of a prepared statement. pdo::param_evt_fetch_pre event triggered prior to fetching a result from a resultset. pdo::param_evt_fetch_post event subsequently triggered to fetch a result from a resultset. pdo::param_evt_normalize event triggered during bound parameter registration allowing the driver to normalize the parameter name.



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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

MantisBT

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools