Mark Mark - 19 days ago 34
PHP Question

How to connect to sql server using PHP7? (What am I missing?)

Here's the phpinfo output: version.php

Here's the code:

$serverName = "X.X.X.X";
$connection = array( "UID"=>"UserID", "PWD"=>"Password123", "Database"=>"database_name");
$conn = sqlsrv_connect( $serverName, $connection);

if ($conn === false) {
$myfile3 = fopen("log.txt", "w");
fwrite($myfile3, sqlsrv_errors());
fclose($myfile3);

};

$tsql = "SELECT top 10 pName from products";
$stmt = sqlsrv_query( $conn, $tsql);
$row = sqlsrv_fetch_array($stmt);

$myfile4 = fopen("log.txt", "w");
fwrite($myfile4, $row[0]);
fclose($myfile4);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);


Nothing is written to the log file. Even if I hard code text in the fwrite($myfile3, "hard coded text"); place, nothing is written out.

Here's the extensions section in the php.ini file

[ExtensionList]
;extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_mbstring.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_curl.dll
extension=php_exif.dll
extension=php_xmlrpc.dll
extension=php_openssl.dll
extension=php_soap.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
extension=php_imap.dll
extension=php_tidy.dll
extension=php_sqlsrv_7_nts_x64.dll
;extension=php_sqlsrv_7_ts_x64.dll


Lastly, I know I don't need all of these, but these are 4 dlls I have in the ext folder.

php_sqlsrv_7_nts_x64.dll
php_sqlsrv_7_nts_x86.dll
php_sqlsrv_7_ts_x64.dll
php_sqlsrv_7_ts_x86.dll

Answer

Using pdo:

$serverName = "(local)\sqlexpress";  

/* Connect using Windows Authentication. */  
try  
{  
  $conn = new PDO( "sqlsrv:server=$serverName ; Database=AdventureWorks", "", "");  
  $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
}  
catch(Exception $e)  
{   
  die( print_r( $e->getMessage() ) );   
} 

Procedural way:

$serverName = "(local)\sqlexpress";  
$connectionOptions = array("Database"=>"AdventureWorks");  

/* Connect using Windows Authentication. */  
$conn = sqlsrv_connect( $serverName, $connectionOptions);  
if( $conn === false )  
die(sqlsrv_errors());  

Click here for More Information

Comments