PHP and SQL Server Introduction

SQL Server is a database that can be used in conjunction with PHP to make websites more dynamic. It can be used to store content and configuration information. PHP can be used to query the data stored within an SQL Server database, as well as insert, update and delete the data.

Connecting to an SQL Server Database

In order to access an SQL Server database with PHP, to either select, insert, update or delete data, you first need to connect to the database. Below is an example of how this can be achieved. For this to work, the necessary drivers need to be downloaded and installed from Microsoft.

<?php

   // Database variables.
   $servername = "localhost\\MSSQLSERVERDEMO";
   $database = "Demo";
   $username = "testUN";
   $password = "testPW";
   
   // Try to connect to the database.
   try {

      $connect = new PDO("sqlsrv:server=$servername;database=$database;",$username,$password);

      // Set the error mode so that exceptions are thrown when SQL statements are executed.
      $connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

   } catch (Exception $e) {

      // If connection fails, display an error and exit.
      echo "Could not connect to the database.";
      exit;

   }
   
   // Display connection successful message.
   echo "Connected to database.";

?>

In this example, a 'try-catch' block is used to catch any exceptions. A 'try-catch' block allows you to handle exceptions in a user-friendly way. In this instance, it will try to connect to the database and if it fails an error message will be displayed. Note the 'exit' command after the displaying of the error message. This basically stops the execution of the PHP script, so the message about connecting to the database successfully will not be displayed if the connection fails.