How to make a connection to a database in Microsoft SQL Server using PHP

Home > Search > How-to
  by

Before a connection can be made to a database in Microsoft SQL Server, you must have done the following:

 

Following is an example of the PHP used to make a connection to a database in Microsoft SQL Server.

<?php
$ServerName = "Computer1\Instance1";
$ConnectionString = array("Database"=>"database_name", "UID"=>"user1", "PWD"=>"password");
$con = sqlsrv_connect( $ServerName, $ConnectionString);

if( $con ) {
     echo "Connection established.<br />";
}
else {
     echo "Connection could not be established.<br />";

die( print_r( sqlsrv_errors(), true))
;}
?>

Notice this PHP requires 4 pieces of unique data:

Server Name
This is the Server name that displays when making a connection using SQL Server Managment studio. In this screen shot, the Server name is Computer1\\Instance1. In this example, Computer1 is the name of the computer, and Instance1 is the name of the SQL Server instance.

Database Name
This is the database listed after a successful connection is made using SQL Server Management Studio.

Username (UID)
This is the Login name that displays when making a connection using SQL Server Managment studio. In this screen shot, the Login is user1.

Password (PWD)
This is the password that displays when making a connection using SQL Server Managment studio. In this screen shot, the password is ******** (when not hidden, the password is "password").



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments