[英]Can't Connect to local server using PDO?
I have been playing around for PHP with a while. 我玩PHP已有一段时间了。 This is how i connect to sql server and it works: 这是我连接到SQL Server的方式,它的工作原理是:
$serverName = "SNAME";
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"USERNAME", "PWD"=>"PASSWORD");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT X FROM myTable";
$query = sqlsrv_query($conn,$sql);
if ($query === false){
echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{
$ARRAY[] = "$row[X]";
}
Server SNAME is on the local network, and i can connect to it from my computer using Sql Management Studio. 服务器SNAME在本地网络上,我可以使用Sql Management Studio从我的计算机连接到它。
Now looking online and other places I have realized PDO is the better way to go. 现在在网上寻找其他地方,我已经意识到PDO是更好的选择。 So I have been trying to connect to my server using PDO, by following examples online. 因此,我一直尝试通过在线示例通过PDO连接到我的服务器。 Here is the code: 这是代码:
$username = "USERNAME";
$password = "PASSWORD";
try{
$conn = new PDO('mysql: host=SNAME;port=1433;dbname=DBNAME',$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT X FROM myTable');
foreach($data as $row) {
print_r($row);
}
}
catch{
echo 'ERROR: ' . $e->getMessage();
}
When i run this i get this on my page: 当我运行它时,我在页面上得到了这个:
ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. 错误:SQLSTATE [HY000] [2002]无法建立连接,因为目标计算机主动拒绝了该连接。
Now i know my other information is right since i can use the top block and sql management studio. 现在我知道我的其他信息是正确的,因为我可以使用top block和sql management studio。 Is there anyother library or something special needed. 还有其他图书馆还是需要一些特殊的东西。 Is there problem with my code? 我的代码有问题吗?
UPDATE I ran this in my SQL Management Studio to check my port and it gave me 1433. 更新我在SQL Management Studio中运行了此程序以检查我的端口,它给了我1433。
SELECT DISTINCT local_tcp_port FROM sys.dm_exec_connections WHERE local_tcp_port IS NOT NULL
In one example, you are using sqlsrv_connect
, but in the other you tell PDO to connect to a 'mysql:'
database. 在一个示例中,您使用的是sqlsrv_connect
,但在另一个示例中,您告诉PDO连接到'mysql:'
数据库。
You need to use the correct DSN string for a SQL Server connection. 您需要为SQL Server连接使用正确的 DSN字符串。
$conn = new PDO('sqlsrv:Server=SNAME,1433;Database=DBNAME',$username,$password);
Manual: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php 手册: http : //php.net/manual/zh/ref.pdo-sqlsrv.connection.php
PS Make sure you have PDO_SQLSRV
installed. PS确保已安装PDO_SQLSRV
。 http://php.net/manual/en/ref.pdo-sqlsrv.php http://php.net/manual/zh/ref.pdo-sqlsrv.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.