Escaping in MSSQL

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Escaping in MSSQL

Post by alex.barylski »

I have a simple query where I am passing in some GPC data like so:

Code: Select all

$name = addslashes($name);
 
$sql = "SELECT mcats_id FROM MBR__CLASSIFIED_ADVT__TYPE__SUB WHERE mcats_type = '$name' AND mcat_id = '$cat_primary'";
$res = odbc_exec($odbc_ptr, $sql);
addslashes() doesn't seem to do the trick. The field is actually labeled SUV's and therefore I cannot strip the single quote otherwise the search will fail.

How do I escape the SQL query so I may include the 's in the query?

Cheers,
Alex
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Escaping in MSSQL

Post by Christopher »

Have you tried obdc_prepare() ? Also you may have to convert single quotes to two single quotes instead of escaping with slash.
(#10850)
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Escaping in MSSQL

Post by alex.barylski »

Two single quotes sounds like the suggested solution -- although I tried ''$title'' and it still didn't do the trick my DBA made some changes and all seems to work for now.

Thanks :)

Cheers,
Alex
User avatar
HCBen
Forum Commoner
Posts: 33
Joined: Thu Jun 22, 2006 3:15 pm
Location: Indiana

Re: Escaping in MSSQL

Post by HCBen »

I use a custom function:

Code: Select all

function _sqlString($string)
{
    if (is_string($string)) return "'".str_ireplace("'","''",$string)."'";
    elseif (is_null($string)) return "NULL";
    else return $string;
}
Like so:

Code: Select all

$sql = "SELECT mcats_id FROM MBR__CLASSIFIED_ADVT__TYPE__SUB WHERE mcats_type = "._sqlString($name)." AND mcat_id = "._sqlString($cat_primary)." ";
Post Reply