MSSQL DATABASE CONNECTION WITH PHP

时间:2017-08-04 12:16:53

标签: php sql sql-server

Please i am trying to connect to an mssql database on a different machine. Below is my code but i just keep getting a blank page.

I dont know what the issue may be. i have installed php and the mssql drivers.

<?php

    $uid = "******";
    $pwd = "***\$\$****";
    $DB = "***********";
    $serverName = "192.***.**.***";
    $connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=> $DB, "ReturnDatesAsStrings" => true);
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{

     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}

?>

2 个答案:

答案 0 :(得分:0)

I would suggest that you display the connection error using sqlsrv_errors().

Load the PHP drivers in php.ini file and restart the server.

extension=php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll

Please see the following example:

<?php
   $serverName = "serverName\sqlexpress"; //serverName\instanceName

   // Since UID and PWD are not specified in the $connectionInfo array,
   // The connection will be attempted using Windows Authentication.
   $connectionInfo = array( "Database"=>"dbName");
   $conn = sqlsrv_connect( $serverName, $connectionInfo);

   if( $conn ) {
     echo "Connection established.<br />";
   }else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
   }
?>

For more info: http://php.net/manual/en/function.sqlsrv-connect.php

答案 1 :(得分:0)

这适用于Server 2019和PHP 7.4。

下载SQLSRV 5.8.0驱动程序here

在您的php.ini文件中有此代码:(取决于硬件32与64)

extension=pdo_sqlsrv_74_ts_x64
extension=sqlsrv_74_ts_x64

使用此命令创建mssql连接:

Function connect_db() {
            $this->connectionInfo = Array("UID" => DB_USER, "PWD" => DB_PASSWORD, "Database" => DB_NAME);
            $this->conn = SQLSRV_CONNECT(DB_SERVER, $this->connectionInfo);
            if ($this->conn){ return; }
            else {echo "Error";die( print_r( sqlsrv_errors(), true ));}
        }