search
HomeBackend DevelopmentPHP TutorialSummary of the differences in PDO database operations between PHP 5.1.* and 5.2.*_PHP Tutorial

介绍
今天发现php5.1.*和php5.2.*在数据库预编译代码执行的时候出现差异。
预编译优点
1.使用占位符,避免逐字输入数据到SQL中。自动处理引号和反斜线等字符的转义——增加安全性。
2.预先“准备”一条语句,然后在每次执行时绑定不同值达到重用的目的。——常用于以后被多次执行的语句。
3.可读性强。

代码
数据库连接代码都一样.

复制代码 代码如下:

$protol = 'mysql:host=localhost;dbname=test';
$username = 'monty';
$passwd = '0818';
$dbh = new PDO($protol, $username, $passwd);

以下是一些测试。注意里面的SQL和for或者foreach语句!
测试1(用key值进行绑定)
复制代码 代码如下:

$stmt = $dbh->prepare('select * from t1 where name=:name');
$params = array();
$params['name'] = 'rentao';
foreach($params as $k=>$v){
$stmt->bindParam($k, $v);
}
$stmt->execute();
$item = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
var_dump($row);
}
$stmt = null;
$dbh = null;

结论:
PHP 5.1.* PHP 5.2.*
执行正常 执行正常
$params['name'] = 'rentao' 和$params[':name']='rentao'这两个都能执行,说明不受“:”限制。
测试2(数字下标去绑定,但是绑定的起始参数是1)——":key"在php5.2.*上不能用数字下标绑定

复制代码 代码如下:

$stmt = $dbh->prepare('select * from t1 where name=:name limit 2');
$params = array();
$params[] = 'rentao';// 这里加不加":"都能成功执行


for($i=0,$iLen = count($params); $i $k = $i+1;
$stmt->bindParam($k, $params[$i]);
}
echo "HERE1\n";
$stmt->execute();
echo "HERE2\n";

$item = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
var_dump($row);
}
$stmt = null;
$dbh = null;

结论:
php 5.1.* PHP 5.2.*
执行正常 出现错误:“PHP Warning:  PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined”
如果把":name"改成"?",那么两个版本都可以顺利进行。
不能同时使用两种符号。如 select * from t2 where name=? limit :page
测试3(limit绑定:page)
复制代码 代码如下:
$stmt = $dbh->prepare('select * from t2 where name=:name limit :page');
$params = array();
$params['name'] = 'rentao';// 这里加不加":"都能成功执行
$params['page'] = 2;
foreach($params as $k=>$v){
$stmt->bindParam($k, $v);
}
$stmt->execute();
echo "HERE1\n";
$item = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
var_dump($row);
}
echo "HERE2\n";
$stmt = null;
$dbh = null;

结论:
PHP 5.1.* PHP 5.2.*
执行到$stmt->execute()时,进程一直处于等待状态中 执行正常:打印不出结果
Test 4 (precompile operation under limit: page) - use the "?" mechanism to run
Copy code The code is as follows:

$stmt = $dbh->prepare('select * from t2 where name=? limit ?');
$params = array();
$params[] = 'rentao';
$params[] = 2;
for($i=0,$iLen = count($params); $i $k = $i+1;
$stmt->bindParam($k, $params[$i]);
}
$stmt->execute();
$item = array ();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
var_dump($row);
}
$stmt = null;
$ dbh = null;

PHP 5.1.* PHP 5.2.*
执行正常 执行正常:打印不出结果
Test 5---order by)
PHP 5.1.* PHP 5.2.*
打印出结果,但未按order by进行排序 执行正常:打印不出结果
Summary
When PHP uses PDO for database pre-compilation operations, try to avoid using limit, order by, group by for pre-compilation processing. We try to use unified standards for bind variables, otherwise we use "?", otherwise we use ":key".

Useful command, I tested it on php5.1.*. After the test, I transferred the file to the php5.2.* server through scp.
Copy Code The code is as follows:
scp -P9888 index.php rentao@192.168.10.4:/home/rentao

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325264.htmlTechArticleIntroduction Today I found that there are differences between php5.1.* and php5.2.* when the database precompiled code is executed. . Advantages of precompilation 1. Use placeholders to avoid entering data into SQL verbatim. Automatically process quotes...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.