PHP MSSQL connection script using PHP MSSQL driver

PHP MSSQL connection script using PHP MSSQL driver

You can use different database servers viz. MySQL, MariaDB, Microsoft SQL Server etc. in your PHP code to connect your database and fetch the data.

It is possible to connect to SQL server using PHP script. There is PHP MSSQL driver available which can be used to connect to Microsoft SQL server from PHP script. Following is the sample script to connect to your SQL server from your PHP script:

$serverName = "SQL Server";
$uid = "sql_username";
$pwd = "sql_user_password";
$databaseName = "DBName";
$connectionInfo = array("UID"=>$uid,"PWD"=>$pwd,"Database"=>$databaseName);   

$conn = sqlsrv_connect( $serverName, $connectionInfo);    
$sqlquery = "SELECT id, FirstName, LastName, Email FROM tblName";
$stmt = sqlsrv_query( $conn, $sqlquery);    
if ( $stmt )    
     echo "Query executed successfully.<br>\n";    
     echo "Error in query execution.\n";    
     die( print_r( sqlsrv_errors(), true));    

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))    
     echo "Col1: ".$row[0]."\n";    
     echo "Col2: ".$row[1]."\n";    
     echo "Col3: ".$row[2]."<br>\n";    
     echo "-----------------<br>\n";    
/* Free statement and connection resources. */    
sqlsrv_free_stmt( $stmt);    
sqlsrv_close( $conn);    

You will have to make sure that PHP MSSQL driver is installed on the server and it has been enabled in PHP configuration file (php.ini).

This Post Has One Comment

  1. Kevin

    Thank you for sharing a sample MSSQL and PHP script code.

Leave a Reply