PDO and php - Call to a member function prepare() on a non-object

前端 未结 2 764
你的背包
你的背包 2021-01-23 13:14

I started learning PDO and im still a bit of a PHP novice. Im doing a project to increase my knowledge but im stuck at the first hurdle.

Im getting this error: Call to a

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 13:32

    Get same error and couldn't fix with code written above.

    Here is easy fix as in your code this is the problem why PDO Sending Error :

    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }
    

    I am using PHP 5.5 and if someone have same error then he will need this

    After $dns you need to add this where $this->dbname . ";";

    Only this is how it will work for PHP 5.5 and Will not work with $this->dbname . "'";

    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ";";
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }
    

提交回复
热议问题