PHP connection to MS SQL



我试图连接我的PHP网页与我的MS SQL数据库。我从互联网上得到了这个代码,但我试过其他人。似乎所有回来的问题与"mssql_connect"。

我什么都试过了(我想),但还是不知道为什么行不通。

我的代码是:
<?php
$myServer = 'SQL5008.Smarterasp.net,1433';
$myUser = '*****';
$myPass = '*****';
$myDB = '*****'; 
//connection to the database
$dbhandle = mssql_connect($myServer, $myuser, $myPass)
or die("Couldn't connect to SQL Server on $myServer"); 
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB"); 
//declare the SQL statement that will query the database
$query = "SELECT id ";
$query .= "FROM tblEmployees ";
$query .= "WHERE CompanyID=3"; 
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result); 
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>"; 
//display the results 
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>

为什么不试试PDO呢?我每天都在SQL SERVER上使用它。不过,您需要php sqlsrv扩展。

// instantiate the pdo object
try {
    $Server = "localhost";
    $User = "username";
    $Pass = "password";
    $Database = "mydb";
  
    $this->conn = new PDO("sqlsrv:Server=$Server;Database=$Database", $User, $Pass);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//allow for SQL query errors
    }
catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
    }

检查是否加载了mssql扩展。根据PHP手册:

此扩展在PHP 5.3或更高版本的Windows上不再可用。

如果您发现mssql已卸载,请尝试使用sqlsrv扩展连接。这里可以找到一些例子http://php.net/manual/ru/function.sqlsrv-connect.php

无论如何,在这里发布从PHP获得的错误消息是一个好主意。

最新更新