php oop pdo连接被拒绝了吗?

时间:2017-05-21 00:37:06

标签: php pdo

我正在尝试使用connect to database,但是我收到此错误,我在php终端上运行它。

我检查了其他来源,例如one,但没有找到我想要的答案

任何建议或最佳做法?

SQLSTATE[HY000] [2002] Connection refusedsomething went wrong

db.php中

<?php 

error_reporting(-1);

class Db{

    private $db_host;
    private $db_user;
    private $db_name;
    private $db_pass;

    public function __construct()
    {
        $this->db_host = "127.0.0.1";
        $this->db_user = "root";
        $this->db_pass = "";
        $this->db_name = "eli9";

        try{
            $pdo = new PDO("mysql:host=127.0.0.1;dbname=eli9", $this->db_user, $this->db_pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            echo "connected sucessfully \n";

        }

        catch(PDOexception $e){
            echo $e->getMessage();

            echo "something went wrong \n";
        }

    }


}

的index.php

<?php

require_once 'Db.php';

$db = new Db();

2 个答案:

答案 0 :(得分:0)

试试这个,适合我

$pdo = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);

您将变量设置为$this->db_host = "127.0.0.1"但未使用连接

在没有上课的情况下尝试此操作,直到您连接并使用$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);检查是否有任何错误

还尝试端口8889

try {
    $db = new PDO("mysql:host=127.0.0.1;port=3306,dbname=eli9", 'root', '');
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    echo "connected";
    } 
catch (PDOException $e){
    echo $e->getMessage();
    }

答案 1 :(得分:0)

在@addie代码的帮助下,我找到了问题,它是以下

1)我最初没有使用端口号

2)我将端口号更改为8889而不是3306

所以这是Db.php的最终代码

<?php 

error_reporting(-1);

class Db{

    private $db_host;
    private $db_user;
    private $db_name;
    private $db_pass;

    public function __construct()
    {
        $this->db_host = "127.0.0.1";
        $this->db_user = "root";
        $this->db_pass = "root";
        $this->db_name = "eli9";

        try {
            $db = new PDO("mysql:host=127.0.0.1;port=8889,dbname=eli9", 'root', 'root');
            $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
            echo "connected";


        } 
        catch (PDOException $e){
            echo $e->getMessage();
        }


    }


}

谢谢你@addie,但是我的普遍问题是为什么我需要在pdo中包含port,如果那不是php手册?