使用PDO出现了一个问题,当字符的最后一个为\的时候插入数据库失败,很是费解,参数绑定怎么会出现如此的问题?
<code>error_reporting(E_ALL); header("content-type:text/html;charset=utf8"); $params = array(); $params[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES UTF8'; $dsn = "mysql:host=localhost;dbname=test;port=3306;"; $dbh = new PDO($dsn, 'root', '123456', $params); $sql = 'INSERT INTO `fav_ls_1` (`uid`,`fid`,`type`,`title_md5`,`title`,`url`,`order`,`addtime`) VALUES (:uid,:fid,:type,:title_md5,:title,:url,:order,:addtime)'; $bind = array( ':uid' => 5919639, ':fid' => 0, ':type' => 1, ':title_md5' => "0886c9605d1424e656c85736b4730e7f", ':title' => '\\敌\\', ':url' => "http://www.2345.com/?ie", ':order' => 0, ':addtime' => 1449156098, ); $sth = $dbh->prepare($sql); if(false===$sth->execute($bind)) { print_r( $sth->errorInfo () ); } else { echo $dbh->lastInsertId(); }</code>
错误代码如下:
<code>Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'http://www.2345.com/?ie','0','1449156098')' at line 1 )</code>
补充一下:
这个设置了$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);就可以运行了,但是在其他sql上也会出现莫名其妙的错误。
回复内容:
使用PDO出现了一个问题,当字符的最后一个为\的时候插入数据库失败,很是费解,参数绑定怎么会出现如此的问题?
<code>error_reporting(E_ALL); header("content-type:text/html;charset=utf8"); $params = array(); $params[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES UTF8'; $dsn = "mysql:host=localhost;dbname=test;port=3306;"; $dbh = new PDO($dsn, 'root', '123456', $params); $sql = 'INSERT INTO `fav_ls_1` (`uid`,`fid`,`type`,`title_md5`,`title`,`url`,`order`,`addtime`) VALUES (:uid,:fid,:type,:title_md5,:title,:url,:order,:addtime)'; $bind = array( ':uid' => 5919639, ':fid' => 0, ':type' => 1, ':title_md5' => "0886c9605d1424e656c85736b4730e7f", ':title' => '\\敌\\', ':url' => "http://www.2345.com/?ie", ':order' => 0, ':addtime' => 1449156098, ); $sth = $dbh->prepare($sql); if(false===$sth->execute($bind)) { print_r( $sth->errorInfo () ); } else { echo $dbh->lastInsertId(); }</code>
错误代码如下:
<code>Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'http://www.2345.com/?ie','0','1449156098')' at line 1 )</code>
补充一下:
这个设置了$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);就可以运行了,但是在其他sql上也会出现莫名其妙的错误。
感谢king同学的答案:
我的问题是PHP环境是大于5.3.6的,需要在dsn中设置charset=utf8,低于PHP5.3.6版本的使用SET NAMES UTF8
修改代码如下解决:
<code>public function connect($config, $linkNum) { if(empty($this->_link[$linkNum])) { if(empty($config)) $config = $this->config; $params = array(); // PHP') ? "charset={$config['db_charset']};" : ''; $dsn = "{$config['db_type']}:dbname={$config['db_name']};host={$config['db_host']};port={$config['db_port']};" . $dsn_charset; $this->dbName = $config['db_name']; $this->dbType = $config['db_type']; try { $this->_link[$linkNum] = new PDO($dsn, $config['db_user'], $config['db_pass'], $params); $this->_link[$linkNum]->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); $this->_link[$linkNum]->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch(PDOException $e) { throw new CException($e->getMessage()); } } $this->_linkId = $this->_link[$linkNum]; return $this->_linkId; }</code>
注意,把ATTR_EMULATE_PREPARES设置为true并没有真正的用参数绑定功能,这只是模拟
本来默认也是false,不明白为何你要开启它
MySQL的参数绑定是通过prepare语句实现的,如果你的数据库版本支持(MySQL 4.1以上版本支持),不应该开启这个选项!
你的问题很可能是因为这个模拟参数绑定,也就是本质上其实是通过转义实现的出现的错误(推测,未验证)
请见
http://php.net/manual/zh/pdo.setattribute.php

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

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.

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

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

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

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.

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

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


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

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
