php - How to escape wild cards in SQL Server Like Clause -


i using mssql , sqlsrv libraries (cross platform site) php , have had use snippet string sanitation neither library provides mysqli_real_escape_string equivelent.

my function this:

public function sanitize($string) {   if (is_numeric($string) || $string === 'null'           {       return $string;   }    $unpacked = unpack('h*hex', $string);   return '0x' . $unpacked['hex']; } 

the function turns strings hex values cause sql statement in string interpreted string. got somewhere on stack overflow.

however like queries string hello% interpret % wild card after hex encoding. in fact % must hex encoded comparison work.

how ensure user entered wild card characters not interpreted wild card characters?

example query:

select lastname, firstname users usercode 'search string' 

where 'search string' string passed through sanitize function above. add % end of string before query user may put 1 @ beginning or middle or use type of wildcard preventing query succeeding.

i wrote own function , here settled on. still appreciate feedback or better solutions. missing tokens or special characters in list?

function mssqllikeescape($string) {   $new_string = preg_replace('/([\[\]%_\^])/', '[$1]', $string);   return $new_string; } 

example usage:

echo mssqllikeescape('a [ in hand worth % in bush.'); 

results:

a [[] in hand worth [%] in bush. 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -