The following is sample code to connect to an MS SQL database using the php MS SQL driver. Note that the driver only works for SQL 2005 and SQL 2008, not SQL 2000.
| <?php |
| $serverName = "ServerName"; |
| $uid = "sqlusername"; |
| $pwd = "sqlpassword"; |
| $databaseName = "DBName"; |
| |
| $connectionInfo = array( "UID"=>$uid, |
| "PWD"=>$pwd, |
| "Database"=>$databaseName); |
| |
| /* Connect using SQL Server Authentication. */ |
| $conn = sqlsrv_connect( $serverName, $connectionInfo); |
| |
| $tsql = "SELECT id, FirstName, LastName, Email FROM tblContact"; |
| |
| /* Execute the query. */ |
| |
| $stmt = sqlsrv_query( $conn, $tsql); |
| |
| if ( $stmt ) |
| { |
| echo "Statement executed.<br>\n"; |
| } |
| else |
| { |
| echo "Error in statement execution.\n"; |
| die( print_r( sqlsrv_errors(), true)); |
| } |
| |
| /* Iterate through the result set printing a row of data upon each iteration.*/ |
| |
| 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); |
| ?> |
If you run into problems when using this code, please post in our
community forum.
Technical support is unable to assist with specific coding issues.
Article ID: 755, Created On: 1/21/2010, Modified: 8/23/2010