无法使用 PDO 连接到 MySQL 服务器

2022-01-24 00:00:00 connection php mysql pdo host

我有一个用于连接 MySQL 数据库的 PHP 脚本.通过 mysql_connect 进行的连接可以完美运行,但是在尝试使用 PDO 时出现以下错误:

I have a PHP script which I use to connect to a MySQL database. Connection through mysql_connect works perfectly, but when trying with PDO I get the following error:

SQLSTATE[HY000] [2005] Unknown MySQL server host 'hostname' (3)

我用来连接的代码如下:

the code I use to connect is below:

    <?php  
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $hostname_localhost ="hostname";  
    $database_localhost ="dbname";  
    $username_localhost ="user";  
    $password_localhost ="pass";  
    $user = $_GET['user'];  
    $pass = $_GET['pass'];

    try{
        $dbh = new PDO("mysql:host=$hostname_localhost;dbname=$database_localhost",$username_localhost,$password_localhost);
        echo 'Connected to DB';
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare("SELECT check_user_company(:user,:pass)");
        $stmt = $dbh->bindParam(':user',$user,PDO::PARAM_STR, 16);
        $stmt = $dbh->bindParam(':pass',$pass,PDO::PARAM_STR, 32);

        $stmt->execute();

        $result = $stmt->fetchAll();

        foreach($result as $row)
        {
            echo $row['company_id'].'<br />';
        }

        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    } 
    ?>  

提前致谢

推荐答案

遇到了同样的问题.我的解决方案是另一个数据库端口.我写了 localhost:1234 得到了这个错误.

Got the same problem. Mine solution was another database port. I wrote localhost:1234 and got this error.

固定为:

mysql:host=$hostname_localhost;port=1234;dbname=$database_localhost",$username_localhost,$password_localhost);
        echo 'Connected to DB';

相关文章