在Windows上将PHP连接到SQL Server

时间:2019-10-07 18:46:39

标签: php sql sql-server windows

我正在尝试使用PHP连接到SQL Server(MSSQL)数据库。我激活了DBO插件并尝试使用它,但是当我定义对象并运行代码时,出现错误:Connection failed: could not find driver 。从您的代码中可以看到,我已经验证了dbo驱动程序已加载。  我下载了答案之一中链接到的sqlsrv驱动程序,但仍然无法连接。我想念什么? (两个文件index.phpsubmit.php在同一目录中,这就是整个项目)((我在Windows计算机上,但这可能或可能无关))

index.php:

<html>
<head>

</head>
<body>
  <form class="my-form" action="submit.php">
      <input type="text" name="field" />
      <input type="submit" value="Submit" />
  </form>
</body>
</html>

submit.php:

<html>
<head>
</head>
<body>
<h1>page loaded</h1>
<h1><?php if (extension_loaded('pdo')) {
    echo 'pdo extension loaded by php';
} ?></h1>

<?php
$myServer = "xxxxxxxxxxxxxxxx";
$myUser = "xxxxxxx";
$myPass = "xxxxxx";
$myDB = "xxxxxxxxxxxx";


$serverName = $myServer; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>$myDB, "UID"=>$myUser, "PWD"=>$myPass);
$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));
}


?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

mssql *扩展已在PHP 7中删除。

https://www.php.net/manual/en/function.mssql-connect.php

您应该考虑使用PDO。

编辑:

用于MSSQL的PDO需要适当的客户端库,您可以在这里找到: https://docs.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017

不要让自己对版本号(不是PHP版本...)感到困惑,请查看说明,某些驱动程序仅适用于特定的MSSQL服务器版本。

还请注意以下示例: https://docs.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017