How to escape strings in SQL Server using PHP?

前端 未结 14 1483
我寻月下人不归
我寻月下人不归 2020-11-22 09:36

I\'m looking for the alternative of mysql_real_escape_string() for SQL Server. Is addslashes() my best option or there is another alternative funct

14条回答
  •  渐次进展
    2020-11-22 10:04

    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 returns FALSE. The solution for it to work was to download some Microsoft bundles:

    • Microsoft Drivers 3.0 for PHP for SQL Server (SQLSRV30.EXE): Download and follow the instructions to install.
    • Microsoft® SQL Server® 2012 Native Client: Search through the extensive page for the Native Client. Even though it's 2012, I'm using it to connect to SQL Server 2008 (installing the 2008 Native Client didn't worked). Download and install.

    After that you can connect in PHP with PDO using a DSN like the following example:

    sqlsrv:Server=192.168.0.25; Database=My_Database;
    

    Using the UID and PWD 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's PDO::quote(). Enjoy.

提交回复
热议问题