Yaroslav  Osetrov
Yaroslav Osetrov

Reputation: 894

PHP mssql_connect() to Azure Database

I try to set connection with my site and mssql database. I can connect to database, but i can't execute SQL queries. My code is

$connection = mssql_connect('jass8l1.database.windows.net', 'username', 'password');
        if (!$connection){
            print_r(mssql_get_last_message());
        }else{

            $res= mssql_query('SELECT * FROM [my_database].[dbo].[table]', $connection);
            print_r(mssql_get_last_message());
            $row = mssql_fetch_array($res);

            echo $row[0];

        }

This code shows error

Reference to database and/or server name in 'my_database.dbo.table' is not supported in this version of SQL Server.

But when I execute this query online, link MANAGE URL, this error does not occur. How can I solve this problem? Maybe I need some additional driver is for PHP?

Upvotes: 0

Views: 5879

Answers (1)

astaykov
astaykov

Reputation: 30903

The error message cannot be more descriptive than it is!

You simply cannot use the 4-word-notation (i.e. [DB_NAME].[SCHEMA].[TABLE_NAME].[COLUMN]. With SQL Azure you shall always use the 3-word notation (i.e. [SCHEMA].[TABLE].[COLUMN]).

Something more for SQL Azure is that you have to explicitly set Database in your connection. You can not do USE [DB_NAME] in SQL Azure.

When using SQL Azure with PHP I recommend that you go through the How to: Connect to Windows Azure SQL Database from PHP.

You have to alter your connection to something like:

  $serverName = "tcp:ProvideServerName.database.windows.net,1433";
   $userName = 'ProvideUserName@ProvideServerName';
   $userPassword = 'ProvidePassword';
   $dbName = "TestDB";
   $table = "tablePHP";

   $connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);

   sqlsrv_configure('WarningsReturnAsErrors', 0);
   $conn = sqlsrv_connect( $serverName, $connectionInfo);
   if($conn === false)
   {
     FatalError("Failed to connect...");
   }

Also, it is strongly recommended to use Microsoft's MS SQL driver and not the standard PHP provided MSSQL (also referred in the How To).

Upvotes: 3

Related Questions