How can prepared statements be implemented in PHP scripts using sqlsrv to enhance security and prevent SQL injection vulnerabilities?

To enhance security and prevent SQL injection vulnerabilities in PHP scripts using sqlsrv, prepared statements can be implemented. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. This is achieved by parameterizing the SQL query and binding user input to placeholders in the query.

// Establish a connection to the database
$serverName = "localhost";
$connectionOptions = array(
    "Database" => "dbName",
    "Uid" => "username",
    "PWD" => "password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);

// Prepare a SQL query with placeholders
$sql = "SELECT * FROM table WHERE column = ?";
$stmt = sqlsrv_prepare($conn, $sql, array(&$userInput));

// Bind user input to placeholders and execute the query
$userInput = $_POST['input'];
sqlsrv_execute($stmt);

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

// Close the connection
sqlsrv_close($conn);