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?
Edit: Alternative for mysql_error()
would also be useful.
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?
Edit: Alternative for mysql_error()
would also be useful.
i know, litle bit late, but answer from 'Feb 22 '09 at 12:10' by chaos isn`t fit all queries. E.g: "CREATE LOGIN [0x6f6c6f6c6f] FROM WINDOWS" will give you exception
p.s. look at mssql driver for php, http://msdn.microsoft.com/library/cc296181%28v=sql.90%29.aspx and sqlsrv_prepare function, which can binds params.
p.s.s. which also didn`t helps you with query above ;)
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.Abstracted, that would be:
mysql_error()
equivalent ismssql_get_last_message()
.After struggling with this for hours, I've come up with a solution that feels almost the best.
Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.
I use PHP's
PDO::quote()
, but as it comes with PHP,PDO::quote()
is not supported for MS SQL Server and returnsFALSE
. The solution for it to work was to download some Microsoft bundles:After that you can connect in PHP with PDO using a DSN like the following example:
Using the
UID
andPWD
parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection. Now you can use PHP'sPDO::quote()
. Enjoy.You could look into the PDO Library. You can use prepared statements with PDO, which will automatically escape any bad characters in your strings if you do the prepared statements correctly. This is for PHP 5 only I think.
In order to escape single- and double-quotes, you have to double them up:
$value = str_replace( '"', '""', $value );
etc...
and attribution: Escape Character In Microsoft SQL Server 2000
Is not it better to also escape SQL reserved words? For example: