Feb 26, 2013

Windows Azure SQL Database PDO

I faced a problem while trying to connect Windows Azure SQL Database from local system using PDO. Here I'm using PHP 5.4+ and Apache 2.4 on Windows 8. I didn't find better tutorial for trouble shooting.

Following are the steps that explains you what to do..

  1. Download php_pdo_sqlsrv_54_ts.dll and placed it in php/ext directory. Here you can find it
    http://www.microsoft.com/en-us/download/details.aspx?id=20098
    Download SQLSRV30.EXE and extracted to php/ext directory
  2. Open the php/php.ini file and added the following line
    extension=php_pdo_sqlsrv_54_ts.dll
  3. It needs Microsoft SQL Server 2012 Native Client, to go further. So download it from
    http://www.microsoft.com/en-us/download/confirmation.aspx?id=29065
    for 32bits(x86)
    http://go.microsoft.com/fwlink/?LinkID=239647&clcid=0x409
    for 64bits(x64)
    http://go.microsoft.com/fwlink/?LinkID=239648&clcid=0x409
  4. Restart the Apache server.
  5. Write the following code in php file to connect.
    <?php
      $server_url = "xxxxxxx.database.windows.net,1433";
      $db_name = "database_name";
      $db_user = "db_username";
      $db_pwd = "db_pword";
      $conn = new PDO("sqlsrv:Server=tcp:$server_url;Database=$db_name", $db_username, $db_pwd);
      $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    ?>
  6. Fetching data from table
    <?php
      $query = "SELECT * FROM categories";
      $stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
      $stmt->excute();

      while($cat = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo $cat['cat_id']."---".$cat['cat_name']."<br />";
      }
    ?>
That's it...

No comments:

Post a Comment

Want to tell something about this post. Please feel free to write...