PHP Retrieving Error Messages


When a query goes wrong, it is important to fetch the error message(s) returned by the driver to identify the cause of the problem. The syntax is:

sqlsrv_errors([int $errorsOrWarnings]);

This returns an array with:

SQLSTATEThe state that the SQL Server / OBDC Driver is in
codeThe SQL Server error code
messageThe description of the error

It is common to use the above function like so:

$brokenQuery = "SELECT BadColumnName FROM Table_1";
$stmt = sqlsrv_query($conn, $brokenQuery);

if ($stmt === false) {
    if (($errors = sqlsrv_errors()) != null) {
        foreach ($errors as $error) {
            echo "SQLSTATE: ".$error['SQLSTATE']."<br />";
            echo "code: ".$error['code']."<br />";
            echo "message: ".$error['message']."<br />";