What are the best practices for error handling in PHP when using sqlsrv_connect() and sqlsrv_query()?

When using sqlsrv_connect() and sqlsrv_query() in PHP to interact with a SQL Server database, it is important to implement proper error handling to catch any potential issues that may arise during the connection or query execution. This can help in identifying and resolving problems quickly, improving the overall reliability of the application.

// Connect to the SQL Server database
$serverName = "localhost";
$connectionOptions = array(
    "Database" => "dbName",
    "Uid" => "username",
    "PWD" => "password"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);

// Check for connection errors
if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

// Execute a query
$query = "SELECT * FROM tableName";
$stmt = sqlsrv_query($conn, $query);

// Check for query execution errors
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

// Process the query results
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    // Do something with the data
}

// Close the connection
sqlsrv_close($conn);