简体   繁体   中英

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). The simplest scenario is when $text contains a quote, eg $text = "Mc'Donalds"

Inside the ms_escape_string function I try to prevent this by replacing ' with 2 quotes ''. 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)

Everything seems ok - see the double quotes for Mc''Donalds - but it still fails when executing: [mssql_query(): message: Incorrect syntax near 'Mc'

I thought that SET QUOTED_IDENTIFIER might be the culprit so I tried

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

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.

This type of "Escaping in readiness for the next recipient of the data" forms part of the FIEO mantra (Filter Input Escape Output).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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