Table of Contents
Detailed explanation of using PDO method in php, detailed explanation of phppdo
Home Backend Development PHP Tutorial Detailed explanation of using PDO method in php, detailed explanation of phppdo_PHP tutorial

Detailed explanation of using PDO method in php, detailed explanation of phppdo_PHP tutorial

Jul 13, 2016 am 10:10 AM
pdo php method

Detailed explanation of using PDO method in php, detailed explanation of phppdo

This article analyzes in detail the method of using PDO in PHP. Share it with everyone for your reference. The specific analysis is as follows:

PDO::exec: returns an int type, indicating the number of items that affect the result.

Copy code The code is as follows:
PDOStatement::execute

Returns a boolean type, true indicates successful execution, false indicates execution failure, these two usually appear in the following code:

Copy code The code is as follows:
$rs0 = $pdo->exec($sql);
$pre = $pdo->prepare($sql);
$rs1 = $pre->execute();

Generally, you can use the value of $rs0 to determine whether the SQL execution is successful or not. If the value is false, it means that the SQL execution failed, 0 means no changes, and a value greater than 0 means how many records were affected.

But $rs1 can only return whether the SQL execution is successful or not. If you need to get the number of affected records, you need to use $pre->rowCount();

I personally like to use MySQL, so I have these two lines in my extensions.ini.

Copy code The code is as follows:
extension=pdo.so
extension=pdo_mysql.so

Then in the program, the code is as follows:

Copy code The code is as follows:
define('DB_NAME','test');
define('DB_USER','test');
define('DB_PASSWD','test');
define('DB_HOST','localhost');
define('DB_TYPE','mysql');
$dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWD);

The use of constant settings in this article is my personal habit. You don’t have to be as troublesome as me. When doing the above operations, $dbh itself represents the connection of PDO. So how to use PDO?

The first, lazy method query, don’t think about anything, just use the query function as usual, the code is as follows:

Copy code The code is as follows:
$sql = 'select * from test';
foreach ( $dbh->query($sql) as $value)
{
echo $value[col];
};

The second method is to automatically import prepare. After using PDO, I prefer to use the prepare function to perform actions. The advantage of prepare is that you can write the SQL code first and automatically import it later. The information we need.

I think the biggest advantage of this is that it can reduce many security issues compared to using query directly. First, we use prepare to set the SQL code, and then use bindparm to perform the setting action. The code is as follows:

Copy code The code is as follows:
$sth = $dbh->prepare('update db set zh_CN= :str where SN=:SN' );
$sth->bindParam(':str',$str,PDO::PARAM_STR,12);
$sth->bindParam(':SN',$SN);
$sth->execute();

Please pay attention to :str and :SN in the text. When we use the bindParam function, we can use :word to specify the part that the system needs to apply. For example, we use :str and :SN to specify, and the actual content depends on bindParam can also specify the type we want to input.

First of all, let’s look at the specification of :str. :str Since I am sure that the data is text, I use PD::PARAM_STR to tell the program "this is a string" and give it a range, that is, the length is 12 characters Bits.

We can also be less complicated, like :SN, although it is also specified using bindParam, but we omit the type and length, PHP will use the default type of the variable to apply.

Finally, it is to use $sth->execute(); to perform the execution action. It is basically not difficult, it can even be said to be very simple.

If you have a large amount of data that needs to be applied repeatedly, you can desperately reuse bindParam to specify, such as my :str and :SN. If there are ten pieces of data, I can also add it directly to the data like this Library, the code is as follows:

Copy code The code is as follows:
$sth = $dbh->prepare('insert into db ("zh_CN","zh_TW")values (:str , :SN');
foreach ($array => $value )
{
$sth->bindParam(':str',$value[str],PDO::PARAM_STR,12);
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
}

Even strong people like my friend write all possible SQLs at the back of a file. Later, the process SQL part is all brought in with variables. Anyway, the data can be applied in a ready-made way.

Then, if you use the prepare method to select, the keywords can also be specified using: word as above, the code is as follows:

Copy code The code is as follows:
$sth = $dbh->prepare('select * from db where SN = :SN');
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
while($meta = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $meta["name"];
}

The new thing that appears is fetch, which has similar meaning to mysql_fetch_row(), but in fetch() we find an additional thing called PDO::FETCH_ASSOC.

fetch() provides many ways to obtain data, and PDO::FETCH_ASSOC refers to returning the field name and value of the next data

For example, in the above example, use $meta to obtain the data returned by fetch. At this time, the element name of $meta is the field name of the database, and the content is of course the value itself. This is different from when you use mysql_fetch_row(). Because in addition to the field name, mysql_fetch_row() will also give the element name in addition to the field an element based on a serial number. Doesn't PDO have it?

Of course, as long as PDO::FETCH_ASSOC is changed to PDO::FETCH_BOTH, the usage is no different from mysql_fetch_row().

How to troubleshoot

Debugging is an eternal pain for all programmers. How do we debug using PDO?

In fact, PDO already provides two very convenient functions errorInfo() and errorCode()

Usage is also very simple. Whenever we use execute() to execute, if there is an error, there will be content in errorInfo() and errorCode(). We can do it like this. The code is as follows:

Copy code The code is as follows:
$sth = $dbh->prepare('select * from db where SN = :SN');
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
if ($sth->errorCode())
{
echo "There is an error! There is an error!";
print_r($sth->errorInfo());
}

And $sth->errorInfo() will be an array. This array has three values:

0 is SQLSTATE error code

1 is the error code returned by the Driver you are using

2 Error message returned by the Driver you are using

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/933594.htmlTechArticleDetailed explanation of php's use of PDO method, phppdo detailed explanation This article provides a detailed analysis of php's use of PDO method. Share it with everyone for your reference. The specific analysis is as follows: PDO::exec: returns an int type, indicating the impact result...
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

See all articles