W3docs

How to escape strings in SQL Server using PHP?

In PHP, you can use the sqlsrv_real_escape_string() function to escape strings in SQL Server.

In PHP, you can use the sqlsrv_escape_string() function to escape strings for SQL Server. This function takes two parameters: the string to be escaped, and the connection resource. However, using prepared statements is the recommended approach to prevent SQL injection. For example:

Example of escape strings in SQL Server using sqlsrv_escape_string() function in PHP

<?php

$serverName = "your_server";
$connectionInfo = array("Database" => "your_db", "UID" => "your_user", "PWD" => "your_password");
$connection = sqlsrv_connect($serverName, $connectionInfo);

$string = "O'Reilly";
$escapedString = sqlsrv_escape_string($string, $connection);

?>

You can then use the $escapedString variable in your SQL query.

Alternatively, using the PDO library with prepared statements is the most secure way to handle user input and avoid SQL injection.

Example of escape strings in SQL Server using PDO in PHP

<?php

$serverName = "your_server";
$dbName = "your_db";
$username = "your_user";
$password = "your_password";

$string = "O'Reilly";

$pdo = new PDO("sqlsrv:Server=$serverName;Database=$dbName", $username, $password);
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE name = :name");
$stmt->execute([':name' => $string]);

?>

It is important to note that prepared statements are strongly recommended over manual escaping to prevent SQL injection. Always validate and sanitize user input before using it in a query.