简体   繁体   中英

PHP Connect to MS SQL Database

I have a website locally hosted on my computer. My server is using PHP 5.6.21. I am trying to connect to a SQL Database on another computer Microsoft SQL Server 2000.

I have installed the PHP extensions, PHP_sqlsrv_56_ts and PHP_sqlsrv_56_nts. I have enabled them in the php.ini: extension=php_sqlsrv_56_nts.dll extension=php_sqlsrv_56_ts.dll

I have tried to connect using this:

<?php
$serverName = "serverName\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$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));
}
?>

And I tried using this:

<?php 

$connection_string = 'DRIVER={SQL Server};SERVER=<Hector\SQLEXPRESS>;DATABASE=tempdb'; 
$user = 'sqltestclient';
$pass = 'paSSword';
$connection = odbc_connect( $connection_string, $user, $pass ) or die("Unable to connect to server");
echo $connection.' '.$user.' '.$pass;
?>

But neither work, the top wont load the page and the bottom just sasys unable to connect.

Im not sure what Im doing wrong

I was able to solve my problem using the information from this link. http://www.techrepublic.com/article/access-microsoft-sql-server-2000-using-php/

May be this will help:

$serverName = "SERVER\\NAME"; 
$connInfo = array("Database"=>"stockdata");
$conn = sqlsrv_connect($serverName, $connInfo);
if($conn){
 $sql  = "SELECT * FROM users"; 
 $res = sqlsrv_query($conn,$sql);   

 $arr = sqlsrv_fetch_array($res,SQLSRV_FETCH_ASSOC); 

 print_r($arr);



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

If you are using Windows Authentication no need to provide credentials ,otherwise you will get exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM