search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to use php PDO_PHP tutorial

Detailed explanation of how to use php PDO_PHP tutorial

Jul 13, 2016 pm 05:06 PM
pdophpintroduceInstructionsaboutclassmatearticledetailedDetailed explanationEnter

This article will give you a detailed introduction to how to use php PDO. You are welcome to refer to it. Friends who need to know more can save this article.


PDO::exec

The returned type is int, indicating the number of items that affect the result.

PDOStatement::execute

The returned value is boolean, true indicates successful execution, false indicates execution failure.
These two usually appear in:

The code is as follows Copy code
 代码如下 复制代码

$rs0 = $pdo->exec($sql);
$pre = $pdo->prepare($sql);
$rs1 = $pre->execute();

$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.

However, $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

extension=pdo.so

extension=pdo_mysql.so

 代码如下 复制代码

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);

Then in the program, we need to declare PDO?⒍? Tombδ?/p>

Code: [Select]

The code is as follows Copy code

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 constant setting used in this article is my personal habit. You don’t have to be like me? Trouble

When operating like the above, $dbh itself represents the PDO connection
 代码如下 复制代码

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

So what? Use PDO?

The first formula is the lazy method query

Don’t think about anything, just use the query function as usual


Code: [Select]

The code is as follows Copy code

$sql = 'select * from test';

foreach ( $dbh->query($sql) as $value)

{

echo $value[col];
 代码如下 复制代码

$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();

};
The second formula is the automatic bring-in method 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 bring in the data we want later 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 Code: [Select]
The code is as follows Copy code
$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 article. 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
As for the actual content, bindParam can also specify the type we want to input.

首先我们先看:str 的指定,:str 由於我确定资料是属於文字,因此利用PD::PARAM_STR 来告诉程式“这个是字串哟”,并且给一个范围,也就是长度是12个Bit.
We can also avoid that complexity, like :SN. Although it is also specified using bindParam, we omit the type and length. PHP will use the default type of the variable.

Finally, use $sth->execute(); to perform the execution action.

Basically it’s 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

Code: [Select]

The code is as follows Copy code
 代码如下 复制代码

$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();
}

$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 in one file, and then all the subsequent procedural SQL parts will be brought in with variables!
 代码如下 复制代码

$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"];
}

Anyway, the data can be applied in ready-made ways!


Then, if you use prepare to select, of course the keywords can also be specified using :word as above


Code: [Select]

The code is as follows Copy code
$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"];
}



This? The new one is fetch, which has the same meaning as mysql_fetch_row()
But in fetch() we found an extra 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

 代码如下 复制代码

$sth = $dbh->prepare('select * from db where SN = :SN');
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
if ($sth->errorCode())
{
 echo "有错误!有错误!";
 print_r($sth->errorInfo());
}

This is different from when you use mysql_fetch_row(), because in addition to the field name, mysql_fetch_row() will also follow the sequence In addition to the field, the element name is given to 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 the same as 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 Then there will be content in errorInfo() and errorCode() This is how we can do it.... Code: [Select]
The code is as follows Copy code
$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 The error code returned by the Driver you are using
2 Error message returned by the Driver you are using

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630674.htmlTechArticleThis article will give you a detailed introduction to the use of php PDO. You are welcome to enter for reference. If you need to know more Friends can bookmark this article. PDO::exec returns an int type,...
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft