SALES: 1-800-867-1380

How to: Connect to Azure SQL Database Using PHP

Updated: December 6, 2013

You can connect to Microsoft Microsoft Azure SQL Database by using PHP and the SQL Server Driver for PHP starting with version 1.1. This topic shows how to create a PHP application within an Azure Web CGI Role that connects to Microsoft Azure SQL Database. Follow the steps in the Getting Started section of the SQL Server Driver for PHP documentation to prepare your server for developing with PHP and SQL Server. You can download the SQL Server Driver for PHP from the Microsoft Download Center Web site. For more information about SQL Server Driver for PHP, see SQL Server Driver for PHP documentation on MSDN.

noteNote
When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.

Create the Azure application

  1. In Visual Studio, on the File menu, click New, and then select Project.

    noteNote
    You must run Visual Studio as an administrator to use the Azure Development Fabric.

  2. In the Add New Project dialog box, in the Project types list, select Cloud Service for either Visual C# or Visual Basic.

  3. In the Templates pane, select Azure Cloud Service.

  4. Type PHPCGIExample for the Name, and then click OK.

  5. In the New Cloud Service Project dialog box, add a CGI Web Role to the Cloud Service Solution pane, and then click OK.

  6. Create a new PHP folder in your Web role project and copy the files from your PHP installation folder, such as copying c:\program files\PHP to your new PHP folder in the project. The PHP run-time binaries must be part of the deployment.

  7. In Solution Explorer, right-click the WebCgiRole project, point to Add, and then click Existing Item. Browse and add php-cgi.exe to your Web role project.

  8. In the Properties pane for php-cgi.exe, set Build Action to Content and Copy to Output Directory to Copy Always.

Create the PHP application

  1. Edit the web.config file to configure your FastCGI handler. Find the <handlers> section under the <system.webServer> node and add the following:

    <add name="PHP_FastCGI"
         verb="*"
         path="*.php"
         scriptProcessor="%RoleRoot%\approot\php-cgi.exe"
         modules="FastCgiModule"
         resourceType="Unspecified" />
    
  2. Edit the web.roleconfig file to ensure that the <fastCgi> section has the following setting:

    <application fullPath="%RoleRoot%\approot\php-cgi.exe"/>
    
  3. In Solution Explorer, right-click the WebCgiRole project, point to Add, and then click New Item.

  4. In the Add New Item dialog box, select Text File from the Templates pane. Type PHPData.php for the Name, and then click Add.

  5. In the Properties pane for PHPData.php, set Build Action to Content and Copy to Output Directory to Copy Always.

  6. In Solution Explorer, right-click the WebCgiRole project, select Properties. In the Properties window, select Web. In the Start Action pane, click Specific Page and type PHPData.php.

  7. In PHPData.php, paste the following code:

    <?php
    
       $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...");
       }
    
       CreateTable($conn, $table, "Col1 int primary key, Col2 varchar(20)");
    
        
       $tsql = "INSERT INTO [$table] (Col1, Col2) VALUES (1, 'string1'), (2, 'string2')";
       $stmt = sqlsrv_query($conn, $tsql);
       if ($stmt === false)
       {
         FatalError("Failed to insert data into test table: ".$tsql);
       }
       sqlsrv_free_stmt($stmt);
    
       $tsql = "SELECT Col1, Col2 FROM [$table]";
       $stmt = sqlsrv_query($conn, $tsql);
       if ($stmt === false)
       {
         FatalError("Failed to query test table: ".$tsql);
       }
       else
       {
          while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC))
          {
             echo "Col1: ".$row[0]."\n";
             echo "Col2: ".$row[1]."\n";
          }
                                    
          sqlsrv_free_stmt($stmt);
       }
    
       sqlsrv_close($conn);
    
    
    function CreateTable($conn, $tableName, $dataType)
    {
       $sql = "CREATE TABLE [$tableName] ($dataType)";
       DropTable($conn,$tableName);
       $stmt = sqlsrv_query($conn, $sql);
       if ($stmt === false)
       {
          FatalError("Failed to create test table: ".$sql);
       }
       sqlsrv_free_stmt($stmt);
    }
    
    
    function DropTable($conn, $tableName)
    {
        $stmt = sqlsrv_query($conn, "DROP TABLE [$tableName]");
        if ($stmt === false)
        {
        }
        else
        {
          sqlsrv_free_stmt($stmt);
        }
    }
    
    function FatalError($errorMsg)
    {
        Handle_Errors();
        die($errorMsg."\n");
    }
    
    
    function Handle_Errors()
    {
        $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
        $count = count($errors);
        if($count == 0)
        {
           $errors = sqlsrv_errors(SQLSRV_ERR_ALL);
           $count = count($errors);
        }
        if($count > 0)
        {
          for($i = 0; $i < $count; $i++)
          {
             echo $errors[$i]['message']."\n";
          }
        }
    }
    
    ?>
    
    
  8. Press F5 to run the solution.

See Also

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft