搜尋
首頁後端開發php教程mysql - PHP PDO斜杠导致错误问题

使用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

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具