简体   繁体   English

PHP到MsSql查询-转义引号(')问题

[英]Php to MsSql query - escape quotes (') issue

I'm building my query: 我正在建立我的查询:

$q = sprintf("UPDATE testTable SET Text='%s', [Read]=0, TimeUpdated='%s', [From]='%s' WHERE ID='%s'", ms_escape_string($text), $dateReceived, $from, $convID);  

and I execute it: 然后执行它:

$res = mssql_query($q, $dbhandle);

$text should be free text so it could contain all sorts of weird characters (for now let's stick to ASCII). $text应该是自由文本,因此它可以包含各种奇怪的字符(现在让我们继续使用ASCII)。 The simplest scenario is when $text contains a quote, eg $text = "Mc'Donalds" 最简单的情况是$ text包含引号,例如$text = "Mc'Donalds"

Inside the ms_escape_string function I try to prevent this by replacing ' with 2 quotes ''. ms_escape_string函数内部,我尝试通过用2个引号''替换'来防止这种情况。 I echo the query string: 我回显查询字符串:

UPDATE testTable SET Text='Mc''Donalds', [Read]=0, TimeUpdated='2012-08-03 12:44:49', [From]='bogus' WHERE ID='14'

(Note: executing this query from the VS server explorer on the same db works just fine) (注意:在同一个数据库上从VS服务器资源管理器执行此查询就可以了)

Everything seems ok - see the double quotes for Mc''Donalds - but it still fails when executing: [mssql_query(): message: Incorrect syntax near 'Mc' 一切似乎正常-请参见Mc''Donalds的双引号-但执行时仍然失败: [mssql_query(): message: Incorrect syntax near 'Mc'

I thought that SET QUOTED_IDENTIFIER might be the culprit so I tried 我以为SET QUOTED_IDENTIFIER可能是罪魁祸首,所以我尝试了

 $q = "SET QUOTED_IDENTIFIER OFF";
 $resq = mssql_query($q,$dbhandle);

before executing my query but no cigar - I still get the same error. 在执行查询但没有雪茄之前-我仍然遇到相同的错误。

Now I'm stuck - what should I change to get strings containing single quotes to pass through? 现在我被卡住了-我应该怎么做才能使包含单引号的字符串通过?

This question seems more to do with the lack of a native mssql_real_escape_string() function, which is addressed by this thread . 这个问题似乎与缺少本机mssql_real_escape_string()函数有关,此函数可以解决此问题

You should be more worried about an SQL injection attack, a problem many of us have finally put to bed by preferring to use PDO, as has been mentioned in the comments. 您应该更担心SQL注入攻击,正如我们在评论中提到的那样,我们中的许多人最终都倾向于使用PDO来解决这个问题。

This type of "Escaping in readiness for the next recipient of the data" forms part of the FIEO mantra (Filter Input Escape Output). 这种类型的“为下一个数据接收者逃脱准备”是FIEO口头禅(过滤器输入转义输出)的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM