Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape strings in SQL Server using PHP?

I'm looking for the alternative of mysql_real_escape_string() for SQL Server. Is addslashes() my best option or there is another alternative function that can be used?

An alternative for mysql_error() would also be useful.

like image 317
Ali Avatar asked Feb 22 '09 11:02

Ali


People also ask

How do I escape a string in PHP?

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

What is the use of Mysqli_real_escape_string in PHP?

The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations.

What is escape data in PHP?

Escaping is a technique that preserves data as it enters another context. PHP is frequently used as a bridge between disparate data sources, and when you send data to a remote source, it's your responsibility to prepare it properly so that it's not misinterpreted.


1 Answers

addslashes() isn't fully adequate, but PHP's mssql package doesn't provide any decent alternative. The ugly but fully general solution is encoding the data as a hex bytestring, i.e.

$unpacked = unpack('H*hex', $data); mssql_query('     INSERT INTO sometable (somecolumn)     VALUES (0x' . $unpacked['hex'] . ') '); 

Abstracted, that would be:

function mssql_escape($data) {     if(is_numeric($data))         return $data;     $unpacked = unpack('H*hex', $data);     return '0x' . $unpacked['hex']; }  mssql_query('     INSERT INTO sometable (somecolumn)     VALUES (' . mssql_escape($somevalue) . ') '); 

mysql_error() equivalent is mssql_get_last_message().

like image 132
chaos Avatar answered Oct 03 '22 23:10

chaos