How can PHP scripts be improved to prevent SQL injection attacks when accessing databases like MSSQL?

To prevent SQL injection attacks when accessing MSSQL databases in PHP scripts, developers should use parameterized queries with prepared statements. This approach helps to separate SQL code from user input, making it impossible for attackers to inject malicious code into queries.

// Establish a connection to MSSQL database
$serverName = "yourServerName";
$connectionOptions = array(
    "Database" => "yourDatabase",
    "Uid" => "yourUsername",
    "PWD" => "yourPassword"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);

// Prepare a SQL query with parameters
$sql = "SELECT * FROM yourTable WHERE id = ?";
$params = array($id);
$stmt = sqlsrv_query($conn, $sql, $params);

// Fetch results
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    // Process the fetched data
}

// Close the connection
sqlsrv_close($conn);