In-depth understanding of the basic use of PDO in PHP
This article brings you the basic knowledge about pdo. PDO is a major new feature added to PHP5. Our database server is MySQL. All database operations of the program code are performed by a mysql or mysqli() function. Operation, I hope it will be helpful to everyone.
1. Basic knowledge
1. What is PDO?
PDO is the uniform interface of PHP Data Object with a unified interface of PHP operations
2. Why use PDO?
PDO is a major new feature added to PHP5. Our database server is MySQL. All database operations of the program code are operated by a mysql() or mysqli() function. When our database needs to be replaced For example, if it is replaced by SQL, SERVER, PostgreSQL, MS, etc., it is impossible for us to modify all the program codes! So we need to use PDO. PDO helps us solve this problem very well. It is very convenient to use PDO. You only need to modify the data source format and load the corresponding driver file to PHP.ini;
3. What are the characteristics of PDO?
1) Coding consistency
Since the various database extensions available for PHP are written by different publishers, although all extensions provide basically the same features, they are not satisfactory Enough coding consistency. PDO eliminates this inconsistency and provides a single interface that can be used for various databases;
2) Flexibility
Because PDO loads the necessary database drivers at runtime, so No need to reconfigure and recompile PHP every time you use a different database. For example, if the database needs to be switched from SQL to MySQL, you only need to load the PDO_MYSQL driver.
3) Object-oriented features
PDO uses the object-oriented features of PHP5 to achieve more powerful and efficient database communication.
4) High performance
PDO is written in C and compiled to PHP. Compared with other solutions written in PHP, although everything else is the same, it provides more High performance.
2. Basic use of PDO
1. PDO configuration
1) Modify php.ini and add MySQL PDO extension
PHP configuration file php.ini, find the line php_pdo_mysql.dll and remove the semicolon
2) There must be a corresponding extension file in the extension directory
php.ini, find extension_dir, this is the directory where our extension exists. First remove the semicolon in front, and then modify the extension directory. My extension directory is in "E:/Web/php/ext", so change it to extension_dir=" E:/Web/php/ext".
3) PDO is connected to different data. There must be different database -drive files, that is, the extension of the configuration file we add
4) Re -start the server, IIS/Apache, I am, I am, I The one is apache, so that the configuration takes effect
2. Data source configuration format
1) Data source format
(1) Connect to the database, database user name, database name Password
Syntax: $dsn = "Database type: dbname=database name; host=database domain name";
$ User = "Username of Database";
# Series Exam: $ dsn = "mysql: dbname = test;host=127.0.0.1"; 3456";
(2) Declare the object 1 ) Add
2) Query
(1) Query method one:
(2) Generate PDO objects
(3)执行查询
实现代码:
<?php header('content-type:text/html;charset=utf8'); //连接数据库 $dsn="mysql:dbname=test;host=127.0.0.1"; //数据库的用户名 $user="root"; //数据库的密码 $password="123456"; //生成PDO对象 $object = new PDO($dsn,$user,$password); $sql="select * from student"; $result = $object->query($sql); while($arr=$result->fetch()){ print_r($arr); }
查询结果为:
$result的打印结果为:
还可以用:
$data=$result->fetchAll(); print_r($student_info);
输出结果为二维数组:
注释:
1、query()执行查询语句,返回结果集对象;
2、用循环利用fetch()方法逐个的取出记录,返回的是关联数组和索引数组两种数组,和mysql_fetch_array()的返回结果一致
3、fetchAll()方法可以一次取出结果集中所有的数组,以二维数组的形式返回,但仍然是关联数组和索引数组两种数组
数字索引和关联索引都有,属于浪费资源,我们只需要关联索引:还可用用一下方式查询:
$object->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $result = $object->query($sql); $result->setFetchMode(PDO::FETCH_ASSOC); $result_array = $result->fetchAll(); print_r($result_array);
结果为:
注释:
setAttribute()方法是设置部分属性,主要属性有:PDO::ATTR_CASE、PDO::ATTR_ERRMODE等,我们设置的是PDO::ATTR_CASE(使用关联索引获取数据)
PDO::CASE_UPPER是设置关联索引为大写,
PDO::CASE_LOWER -- 强制列名为小写
PDO::CASE_NATURAL -- 列名按照原始方式
PDO::CASE_UPPER -- 强制列名为大写
setFetchMode()方法设置获取结果集的返回值类型,同样类型还有:
PDO::FETCH_ASSOC --关联数组形式
PDO::FETCH_NUM -- 数字索引形式数组
PDO::FETCH_BOTH --两者数组形式都有
PDO::FETCH_OBJ -- 按照对象的形式,类似于以前的mysql_fetch_object()
大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。
The above is the detailed content of In-depth understanding of the basic use of PDO in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
