Use PHP to query an Azure SQL database

This quickstart demonstrates how to use PHP to create a program to connect to an Azure SQL database and use Transact-SQL statements to query data.


To complete this quickstart, make sure you have the following:

  • A server-level firewall rule for the public IP address of the computer you use for this quickstart.

  • You have installed PHP and related software for your operating system:

    • MacOS: Install Homebrew and PHP, install the ODBC driver and SQLCMD, and then install the PHP Driver for SQL Server. See Steps 1.2, 1.3, and 2.1.
    • Ubuntu: Install PHP and other required packages, and then install the PHP Driver for SQL Server. See Steps 1.2 and 2.1.
    • Windows: Install the newest version of PHP for IIS Express, the newest version of Microsoft Drivers for SQL Server in IIS Express, Chocolatey, the ODBC driver, and SQLCMD. See Steps 1.2 and 1.3.

SQL server connection information

Get the connection information needed to connect to the Azure SQL database. You will need the fully qualified server name, database name, and login information in the next procedures.

  1. Sign in to the Azure portal.
  2. Select SQL Databases from the left-hand menu, and click your database on the SQL databases page.
  3. On the Overview page for your database, review the fully qualified server name as shown in the following image. You can hover over the server name to bring up the Click to copy option.


  4. If you forget your server login information, navigate to the SQL Database server page to view the server admin name. If necessary, reset the password.

Insert code to query SQL database

  1. In your favorite text editor, create a new file, sqltest.php.

  2. Replace the contents with the following code and add the appropriate values for your server, database, user, and password.

    $serverName = "";
    $connectionOptions = array(
        "Database" => "your_database",
        "Uid" => "your_username",
        "PWD" => "your_password"
    //Establishes the connection
    $conn = sqlsrv_connect($serverName, $connectionOptions);
    $tsql= "SELECT TOP 20 pc.Name as CategoryName, as ProductName
            FROM [SalesLT].[ProductCategory] pc
            JOIN [SalesLT].[Product] p
         ON pc.productcategoryid = p.productcategoryid";
    $getResults= sqlsrv_query($conn, $tsql);
    echo ("Reading data from table" . PHP_EOL);
    if ($getResults == FALSE)
        echo (sqlsrv_errors());
    while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
     echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);

Run the code

  1. At the command prompt, run the following commands:

    php sqltest.php
  2. Verify that the top 20 rows are returned and then close the application window.

Next steps