When interacting with SQL Server using PHP, it's crucial to ensure that any user-supplied data is properly escaped, preventing SQL injection attacks. While mysql_real_escape_string() is commonly used for MySQL, it's not available for SQL Server.
Unlike MySQL, SQL Server doesn't provide a dedicated function for string escaping. However, you can create your own function:
function mssql_escape($data) { if (is_numeric($data)) { return $data; } $unpacked = unpack('H*hex', $data); return '0x' . $unpacked['hex']; } $escaped_value = mssql_escape($user_input);
This function encodes the data as a hexadecimal bytestring, ensuring that any special characters are escaped.
To retrieve error messages from SQL Server, use mssql_get_last_message():
$error_message = mssql_get_last_message();
This function retrieves the last error message generated by a SQL Server query execution.
Combining these functions, you can securely insert user input into a SQL Server table:
$connection = mssql_connect(...); $query = 'INSERT INTO sometable (somecolumn) VALUES (' . mssql_escape($user_input) . ')'; $result = mssql_query($query, $connection); if (!$result) { $error_message = mssql_get_last_message(); // Retrieve error message }
The above is the detailed content of How to Safely Escape Strings in SQL Server When Using PHP?. For more information, please follow other related articles on the PHP Chinese website!