【问题标题】:PHP connection to MS SQLPHP 连接到 MS SQL
【发布时间】:2015-09-05 11:09:38
【问题描述】:

我正在尝试将我的 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);
?>

【问题讨论】:

  • 尝试删除单引号 $dbhandle = mssql_connect($myServer, $myuser, $myPass)
  • 对不起,我试图将连接字符串作为文本输入。我将编辑我的代码并删除它们。还是没有运气。

标签: php sql-server tsql


【解决方案1】:

您为什么不尝试使用 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();
    }

【讨论】:

  • 我正在使用 php 网页,并且我的数据库是在线托管的。如何获得延期?
【解决方案2】:

如果加载了 mssql 扩展,请使用 phpinfo() 检查。根据 PHP 手册:

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

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

无论如何,在此处发布您从 PHP 获得的错误消息是个好主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2013-05-27
    • 2016-04-24
    • 2016-07-22
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多