如何使用PHP连接到SQL Server

mah*_*aha 11 php sql sql-server database-connection

我想用PHP连接到sql server数据库.

我安装了xampp 1.7.0(php 5.2)和SQLSRV20.我添加了扩展程序php.ini,我收到此错误:

Warning: mssql_connect() [function.mssql-connect]: Unable to connect to 
server: 10.85.80.229 in C:\xampp\htdocs\xampp\test.php on line 07
Run Code Online (Sandbox Code Playgroud)

码:

<?php
$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";

$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer"); 
?>
Run Code Online (Sandbox Code Playgroud)

此错误消息的含义是什么以及如何连接到SQL Server?

Agh*_*med 11

在php.ini中启用mssql

;extension=php_mssql.dll

extension=php_mssql.dll


Har*_*ris 7

<?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);  
?>  
Run Code Online (Sandbox Code Playgroud)

http://robsphp.blogspot.ae/2012/09/how-to-install-microsofts-sql-server.html


Man*_*han 1

使用localhost而不是您的 IP 地址。

例如,

$myServer = "localhost";
Run Code Online (Sandbox Code Playgroud)

并且还要仔细检查您的 mysql 用户名和密码。