通过sqlsrv_connect() - PHP连接到mssql数据库

时间:2014-12-05 03:10:47

标签: php sql-server sqlsrv

我尝试使用sqlsrv_connect()函数使用PHP连接到2005 Microsoft SQL数据库。唉,函数返回false,我不知道为什么。

<?php
$myServer = "MAZE.jpc.wa.edu.au.local";
$myUser = "myUsername";
$myPass = "myPassword";
$myDB = "John Paul College";
$connectionInfo = array("Database"=>$myDB, "UID" => $myUser, "PWD" => $myPass);

$conn = sqlsrv_connect($myServer, $connectionInfo); //returns false
if( $conn === false )
{
    echo "failed connection";
}

$sql = "SELECT name FROM users WHERE name= 'admin'";
$stmt = sqlsrv_query($conn,$sql);
if(sqlsrv_fetch($stmt) ===false)
{
    echo "couldn't fetch data"; 
}
$name = sqlsrv_get_field($stmt,0);
echo $name;
sqlsrv_close( $conn );
?>

有谁知道为什么我无法连接? 感谢。

编辑。

好的,好吧,我能够提出错误信息,感谢其他人回答,其中说明了

Array (
    [0] => Array (
        [0] => IMSSP [SQLSTATE] => IMSSP
        [1] => -49 [code] => -49
        [2] => This extension requires either the Microsoft SQL Server 2008 Native Client (SP1 or later)
                or the Microsoft SQL Server 2008 R2 Native Client ODBC Driver to communicate with SQL Server.
                Neither of those ODBC Drivers are currently installed.
                Access the following URL to download the Microsoft SQL Server 2008 R2 Native Client ODBC driver
                for x86: http://go.microsoft.com/fwlink/?LinkId=163712 
        [message] => This extension requires either the Microsoft SQL Server 2008 Native Client (SP1 or later) 
              or the Microsoft SQL Server 2008 R2 Native Client ODBC Driver to communicate with SQL Server.
              Neither of those ODBC Drivers are currently installed. 
              Access the following URL to download the Microsoft SQL Server 2008 R2 Native Client ODBC driver 
              for x86: http://go.microsoft.com/fwlink/?LinkId=163712 )
    [1] => Array (
        [0] => IM002 [SQLSTATE] => IM002 
        [1] => 0 [code] => 0 
        [2] => [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified 
            [message] => [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ) )

我不完全确定如何解决这个问题。我使用XAMPP作为我的测试网络服务器,php版本5.3和以下.dll php_sqlsrv_53_ts_vc6.dllphp_pdo_sqlsrv_53_ts_vc6.dll

2 个答案:

答案 0 :(得分:3)

我建议您使用sqlsrv_errors()显示连接错误。请参阅以下实施。

<?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));
   }
?>

了解更多信息:http://php.net/manual/en/function.sqlsrv-connect.php

答案 1 :(得分:0)

下载SQL Native Client,如错误消息所示。这与SQL Server分开,并且要求此驱动程序正常工作。在IIS环境中构建sqlsrv实现的经验教训