PDO例外是:“无数据库连接”

时间:2019-07-13 08:51:12

标签: php mysql pdo

我找不到用pdo连接数据库的任何方法;我尝试了以下语法。

我有php7和pdo支持mysql数据库

ConnectDb类:

class ConnectDb {
    private $username = "admin";
    private $password = "passw";
    private $connection = NULL;

    protected function __construct($dbname)
    {
        try
        {
            $connection = new PDO("mysql:host=" . "127.0.0.1" . ";dbname=" . $dbname . ";charset=utf8;",$this->username,$this->password,array(PDO::ATTR_PERSISTENT => true));
            $connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $exception){
            echo $exception->getMessage();
        }
    }

    protected function getConnection()
    {
        return $this->connection;
    }
}

插入数据类

class InsertDb extends ConnectDb
{
    function __construct($dbname)
    {
        parent::__construct($dbname);
        $this->insert();
    }

    private function insert()
    {
        if ($this->getConnection() !== NULL) {
            $savequer = "INSERT INTO customer (first_name, last_name, email, password) VALUES (?,?,?,?)";
            $savedPdo = $this->getConnection()->prepare($savequer);
            $savedPdo->execute(array($_POST['firstName'], $_POST['lastName'],$_POST['email'], $_POST['password']));
        } else {
            echo "No Database Connection";
        }
    }
}

和我的对象

new InsertDb("tamrin01");

无数据库连接

1 个答案:

答案 0 :(得分:0)

在get_connection函数中,您返回类成员连接。但是在构造函数中,您使用的是新变量来创建数据库连接。

就像。

protected function __construct($dbname)
    {
        try
        {
          //Create a database connection with class member connection. Don't use new variable $connection.
            $this->connection = new PDO("mysql:host=127.0.0.1;dbname=$dbname;charset=utf8;",$this->username,$this->password,array(PDO::ATTR_PERSISTENT => true));
            $this->connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $exception){
            echo $exception->getMessage();
        }
    }