How to connect to a MS SQL database in PHP

Overview

PHP connects to a MS SQL database on Everleap through the sqlsrv extension, which is enabled on the platform. You do not need to install anything; you supply the four connection values and call sqlsrv_connect.

Before you start

PHP is not enabled by default. See How to enable PHP.

Step 1: Find your connection details

  1. Log in to the Everleap Control Panel at cp.everleap.com.
  2. From the top menu click Databases, then Shared MS SQL.
  3. The server name, database name and database user name are listed for each of your databases.
The Databases menu in the Everleap Control Panel expanded, showing Shared MS SQL, SQL Reporting Services and Shared MySQL under Shared Cloud Hosting Plan

The password is the one set for that database user, not your Control Panel password.

Step 2: Connect

<?php
$serverName = "Enter Host Name";
$uid = "Enter Username";
$pwd = "Enter Password for SQL User";
$databaseName = "Enter name of the Database";

$connectionInfo = array( "UID"=>$uid,
                         "PWD"=>$pwd,
                         "Database"=>$databaseName);

/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Fill in the four values as follows:

  • $serverName is the server name shown on the Shared MS SQL page.
  • $uid is the database user name shown on the same page.
  • $pwd is that database user's password.
  • $databaseName is the database name shown on the same page.

Verify it worked

Upload the page and open it in a browser. "Connection established." means the four values are correct. "Connection could not be established." is followed by the full error array from sqlsrv_errors(), which will name whichever value is wrong.

A blank page usually means PHP errors are not being displayed rather than that nothing happened. See PHP error logging for where the errors are written.

Notes

Delete or protect the test script once you are finished. It contains a working database user name and password in plain text.

Related Articles