Test Your Configuration

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

If everything works, congratulations!  If not, 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; 
} 

?>

 

Leave a Reply