错误。无法连接到数据库:SQLSTATE [HYT00]

时间:2018-05-26 10:02:37

标签: php linux pdo sqlsrv

尝试使用默认端口号连接到Microsoft SQL Server数据库时出现以下错误:

<?php

class DB_Connect {
    private $db;

    function construct() {
    }

    public function connect() {
        require_once 'String.php';

        try {
            $this->db = new PDO('sqlsrv:Server=$server,1433; Database=$db', $user, $pass);
        } catch (PDOException $e) {
            return "Error. Cannot connect to database: " . $e->getMessage();
        }
    }
}

?>

这是我用来连接数据库的PHP代码:

Int64 number = Convert.ToInt64(textBox1.Text);
do
{
    for (Int64 i = number; i < Convert.ToInt64(textBox2.Text); i++)
    {
        dataGridView1.Rows.Add(textBox3.Text + i);
    }
} while (number == Convert.ToInt64(textBox2.Text));

dataGridView1.Rows.Add(textBox3.Text+textBox2.Text);

我100%确定凭据是正确的,因为当我使用xampp在localhost上运行脚本时它们是正确的。

到目前为止我做了什么:

  • 在linux机器上安装了pdo驱动程序
  • 在linux机器上安装了obdc驱动程序
  • 在linux计算机上安装了sqlsrv驱动程序

enter image description here

这是我在服务器上使用的配置:

PHP版本7.0.30连接到Gearhost上托管的SQL Server 2017。

任何人都可以了解可能出现的问题吗?

2 个答案:

答案 0 :(得分:1)

基本上问题是2:

  1. 首先,驱动程序未正确安装。我需要通过PECL安装驱动程序。这是我在Redhat Cent OS 7上安装它们的方式:
  2. 安装PHP:

    sudo su
    wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
    wget http://rpms.remirepo.net/enterprise/remi-release-7.rpm
    rpm -Uvh remi-release-7.rpm epel-release-latest-7.noarch.rpm
    subscription-manager repos --enable=rhel-7-server-optional-rpms
    yum-config-manager --enable remi-php72
    yum update
    yum install php php-pdo php-xml php-pear php-devel re2c gcc-c++ gcc
    

    安装先决条件

    sudo yum-config-manager --enable rhel-server-rhscl-7-rpms
    sudo yum install devtoolset-7
    scl enable devtoolset-7 bash
    

    为SQL Server安装PHP驱动程序

    pecl download sqlsrv
    tar xvzf sqlsrv-5.2.0.tgz
    cd sqlsrv-5.2.0/
    phpize
    ./configure --with-php-config=/usr/bin/php-config
    make
    sudo make install
    

    安装Apache并重启服务

    sudo yum install httpd
    sudo apachectl restart
    

    <强> - 编辑 -

    您也可以从Github项目页面下载预建的二进制文件,或者从Remi repo安装:

    sudo yum install php-sqlsrv php-pdo_sqlsrv
    
    1. 在我的情况下,我还必须从数据库服务器打开防火墙连接。您检查是否有必要,从终端运行sqlcmd以连接到数据库。如果您使用正确的凭据收到网络错误,那么您就知道您遇到了防火墙问题。
    2. 希望这可以帮助那些正在努力将Linux服务器连接到SQL Server的人。

答案 1 :(得分:0)

你能在这里使用吗?

try{
    $db = new PDO("sqlsrv:Server,1433=$server;dbname=$db;charset=utf8","$user","$pass");
    $query=$db->prepare("Some SQL String Here");
    $query->execute();
}catch(PDOException  $e ){
    echo "Error: ".$e;
}
相关问题