query('select *from user');" and return the result set object."/> query('select *from user');" and return the result set object.">
search
How to use pdo in phpApr 21, 2023 pm 02:24 PM
php pdo usage

pdo in php is an extended class library that can define a lightweight, consistent interface for php. Its usage is as follows: 1. Create a php sample file; 2. Through "try{$link = new PDO(.);}catch(PDOException $e){...}" to create a pdo object; 3. Execute the query through "$link->query('select *from user');" and return the results Just set objects.

How to use pdo in php

This operating system environment: Linux5.18.14 system, Dell G3 computer.

1. Basic concepts

1. PDO: Abbreviation of PHP Data Object. The PDO extension class library defines a lightweight, consistent interface for PHP, which provides a data access abstraction layer so that no matter what database is used, queries and data can be obtained through consistent functions.

PDO is a "database access abstraction layer" that unifies the access interfaces of various databases.

2. Operations on any database are not performed using the PDO extension itself, and must be accessed using specific PDO drivers for different database servers. Such as: MYSQL (PDO_MYSQL). A list of PDO parts can be viewed in the phpinfo() function.

2. PDO installation

1. Linux: When installing PHP, add the following flag to the configure command:

–with-pdo- mysql=/usr/local/mysql ///usr/local/mysql is the mysql installation directory

2. Windows:

Find the php.ini file under C:windows

(1) Open: extension=php_pdo.dll

(2) Open: extension=php_pdo_mysql.dll

3. Use PDO process

1. Connect to the database

2. Create a PDO object:

(1)$link = new PDO(DSN, username, password, driver attribute);

1) DSN: Data source name, used to define a driver that must be used and the database to be used. DSN format of mysql: 'mysql:host=localhost;dbname=lamp30'

2) You can put the DSN in a file, such as: 'uri:file:///usr/local/dsn.txt'

3) Use the try...catch statement when creating an object, because when an error occurs when declaring a PDO instance, an exception will be automatically thrown. For example:

The code is as follows

try{
$link = new PDO(‘mysql:host=localhost;dbname=lamp30’,’root’,’111111’);
}catch(PDOException $e){
echo $e->getMessage();
exit(‘连接数据库错误.’);
}

3. Drive attribute

(1) You can form an array with several necessary options (the attribute name is used as the element key, and the attribute value is used as the element value) is passed to the fourth parameter of the constructor. If the driver attribute is not defined in the constructor, you can later use the setattribute() function of the PDO class to define each attribute.

(2) There are Chinese explanations of these attributes on page P501 of the book.

3. Set character set: $link->query('set names UTF8')

5. Send SQL statement

(1 )$link->exec(): Execute additions, deletions and modifications, and return the number of affected rows. If the execution fails, it returns false or 0.

(2)$link->query(): Execute the query and return the PDOStatement result set object.

6. Query results

1. Non-query:

(1) Directly use the affected rows returned by $link->exec() Number

(2)$link->lastInsertId() returns the AUTO_INCREMENT number value generated by the last INSERT command

2. See Preprocessing

7. Preprocessing

1. Step 2: Send SQL statement

The code is as follows

$stmt = $link->prepare(‘select * from user where id=:id’);
$stmt->bindparam(‘:id’, $id, PDO::PARAM_INT);
$id = 2;
$stmt->execute();

bindParam() parameters have the following 7 types: you don’t need to write

PDO::PARAM_INT

PDO::PARAM_STR

PDO::PARAM_BOOL

PDO::PARAM_NULL

PDO::PARAM_LOB: Large Object Data type

PDO::PARAM_STMT: PDOstatement type

PDO::PARAM_INPUT_OUTPUT: Data type used by the stored procedure

2. Step 3:

For example:

The code is as follows

$stmt = $link->query(‘select * from user’);

(1)fetch() method

$pdoStat ->bindColumn(1, $id); //第一个参数可以是从1开始的索引值
$pdoStat ->bindColumn(‘name’, $name); //也可以是列名
$pdoStat ->bindColumn(‘pass’, $pass);
while($row = $stmt ->fetch(PDO::FETCH_BOUND)){
echo $id.’ ’;
echo $name.’ ’;
echo $pass.’
’;
}

There are six parameters for fetch(): see the manual.

You can use the setFetchMode() method to set the default mode.

(2)fetchall() method

The code is as follows

$result = $stmt ->fetchall();
foreach($result as $row){
echo $row[‘id’].’ ’;
echo $row[‘name’].’ ’;
echo $row[‘pass’].’
’;
}

Fetchall() parameters are the same as fetch().

8. Transaction processing

1. Turn off automatic submission (modify in driver properties)

2. Open transaction

3. Commit transaction/rollback

4. Turn on automatic submission

For example:

The code is as follows

$link = new PDO(‘mysql:host=localhost;dbname=lamp30’);
//1
$link->setattribute(PDO::ATTR_AUTOCOMMIT, false);
//2
$link->begintransaction();
$result = $link->exec(‘insert into user(name,paa) values(‘wsy’,’111’)’);
//3
if($result){
$link->commit();
}else{
$link->rollback();
}
//4
$link->setattribute(PDO::ATTR_AUTOCOMMIT, true);

9. In the PDO object Member methods

1, $link->getattribute (attribute name): Get a driver attribute.

2. $link->setattribute (attribute name, attribute value): Set a driver attribute.

1) Because Oracle returns empty strings as NULL values, and other databases do not have this feature, in order to have better compatibility $link->setattribute(PDO::ATTR_ORACLE_NULLS,PDO::NULL_EMPTY_STRING, );

2) There are three ways to display errors: static, WARNING message, exception

3, $link->errorcode(): Get the error code.

1) If the setattribute function sets the error display mode to static, nothing will be displayed when an error occurs. This function must be called to view the error number.

4. $link->errorinfo(): Get error information (array).

1) If the setattribute function sets the error display mode to static, nothing will be displayed when an error occurs. This function must be called to view the error message.

5. $link->lastinsertid(): Get the primary key value of the last data inserted into the table (if multiple pieces of data are inserted at the same time, return the ID of the first inserted row).

6、$link->prepare():发送准备的SQL语句,返回PDOStatement对象。

7、$link->begintransaction():打开事务。

8、$link->commit():提交一个事务,执行一个SQL。

9、$link->rollback():回滚一个事务。

十、错误模式

1、静态模式:

代码如下

$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT)

(1) 默认模式,在错误发生时不进行任何操作,PDO将只设置错误代码。

(2) 查看错误可以调用errorCode()和errorInfo(),PDO和PDOStatement类都有这两个方法。

2、警告模式:

代码如下

$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING)

(1)此模式在设置错误代码以外,PDO还将发出一条PHP传统的E_WARNING消息。

(2)这是mysql和mysqli显示错的方式。

3、异常模式:

代码如下

$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)

(1) 此模式在设置错误代码以外,PDO还将抛出一个PDOException,并设置其属性,以反映错误代码和错误信息。

(2) 如果异常导致脚本终止,则事务将自动回滚。

(3) PDO推荐使用此模式。

十一、持久连接

代码如下

$link->setAttribute(PDO::ATTR_PERSISTENT, true);

持久连接即当脚本执行结束时不会自动断开连接,而且用$link->close()不能关闭连接。

The above is the detailed content of How to use pdo in php. For more information, please follow other related articles on the PHP Chinese website!

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 are the best practices for deduplication of PHP arraysWhat are the best practices for deduplication of PHP arraysMar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Does PHP array deduplication need to be considered for performance losses?Does PHP array deduplication need to be considered for performance losses?Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

Can PHP array deduplication take advantage of key name uniqueness?Can PHP array deduplication take advantage of key name uniqueness?Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

How to Implement message queues (RabbitMQ, Redis) in PHP?How to Implement message queues (RabbitMQ, Redis) in PHP?Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices?What Are the Latest PHP Coding Standards and Best Practices?Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

What are the optimization techniques for deduplication of PHP arraysWhat are the optimization techniques for deduplication of PHP arraysMar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

How Do I Work with PHP Extensions and PECL?How Do I Work with PHP Extensions and PECL?Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code?How to Use Reflection to Analyze and Manipulate PHP Code?Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools