Home Backend Development PHP Tutorial Detailed explanation of usage of php pdo function library

Detailed explanation of usage of php pdo function library

Jul 25, 2016 am 08:54 AM

  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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

See all articles