What are the best practices for preventing SQL injection in PHP when using MS-SQL Server?
SQL injection can be prevented in PHP when using MS-SQL Server by using prepared statements with parameterized queries. This approach allows the database engine to distinguish between SQL code and user input, preventing malicious code execution.
// Establish a connection to the MS-SQL Server
$serverName = "serverName";
$connectionOptions = array(
"Database" => "dbName",
"Uid" => "username",
"PWD" => "password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);
// Prepare and execute a parameterized query
$tsql = "SELECT * FROM Users WHERE username = ?";
$params = array($username);
$stmt = sqlsrv_query($conn, $tsql, $params);
// Fetch results
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['username'] . "<br />";
}
// Close the connection
sqlsrv_close($conn);