Test Your Installation

  1. Open SQL Server Management Studio
  2. Create a SQL user with a password
  3. Create a database named “MyDatabase”
  4. Create a table in MyDatabase named TestTable
  5. Add two columns to TestTable
  6. Create login name “TestUser”
  7. Create a password “Tpass_PHPConnect”
  8. Add a user to the database you created above
  9. Assign read/write permissions to the user for the database you assigned the user to.
  10. Create a PHP script with the lines below and save it in your document root directory under the file name TestConnection.php
  11. Open a browser, and enter “http://localhost/TestConnection.php” as the URL

 

If everything works, congratulations!
If not, make a note of the error messages you get, and go to the trouble shooting section.
<?php
 // edit the lines between here and the next comment 
 // using values from your installation 
$DBName = "MyDatabase"; 
$user = "TestUser";
$pass = "Tpass_PHPConnect";
$host = "localhost";

$stmt = "select * from TestTable";
 // edit the lines between here and the previous comment 
$conn = DBConnect($DBName, $user, $pass,$host); 
echo "$conn <br>"; 
DBError(); 
$userData = sqlsrv_query($conn,$stmt, array(), array("Scrollable"=>"buffered")); DBError(); 
$gotrows = sqlsrv_has_rows($userData); if (!$gotrows) { 
$e = "WARNING No Rows found for SQL statement $stmt"; 
echo "$e <br>"; 
}

While( $row = sqlsrv_fetch_array( $userData, SQLSRV_FETCH_ASSOC) ) { 
   $t = $row['returnoptions']; 
   echo "Selected Value => $t<br>";
} 
$d = DBDisconnect($conn); DBError();


function DBDisconnect($conn) { 
$rtn = sqlsrv_close( $conn ); 
if ($rtn) { 
   $result = "SUCCESS $conn"; } else { 
   $result = "ERROR $conn"; } 
   echo $result; 
   return $result; 
}


function DBError() { 
//echo "entering dberror"."<br />"; 
$errmessage = "";
$rtn = false; 
// returns true if no errors are found, else false 
if( ($errors = sqlsrv_errors() ) !== null) { 
 $rtn = true; //there was an error 
 foreach( $errors as $error ) { 
 $errmessage = "SQLSTATE ERROR: ".$error[ 'SQLSTATE']; 
 echo $errmessage;
 $errmessage = "code: ".$error[ 'code'];
 echo $errmessage; 
 $errmessage = "message: ".$error[ 'message']; 
 echo $errmessage;
 } 
} 
return $rtn;
}

function DBConnect($DBName, $user, $pass, $host) { 
$connectinfo = array( "Database"=>$DBName, "UID"=>$user, "PWD"=>$pass); 
$r = sqlsrv_connect( $host, $connectinfo); 
if( ($errors = sqlsrv_errors() ) !== null) { 
   $rtn = true; 
   //there was an error 
   foreach( $errors as $error ) { 
     $errmessage = "SQLSTATE ERROR: ".$error[ 'SQLSTATE']; 
     echo $errmessage."<br>";
     $errmessage = "code: ".$error[ 'code'];
     echo $errmessage."<br>"; 
     $errmessage = "message: ".$error[ 'message']; 
     echo $errmessage."<br>"; 
  } 
} 
return $r; 
}

?>