【问题标题】:Call to a member function prepare() on a non-object PHP PDO在非对象 PHP PDO 上调用成员函数 prepare()
【发布时间】:2018-10-20 03:33:05
【问题描述】:

你能帮帮我吗?我的脚本有点问题。

database.php

class Database {

    protected $host = "localhost";
    protected $dbname = "phppdo";
    protected $user = "root";
    protected $pass = "";
    protected $DBH;

    public function __construct() {
        try {
            $this->DBH = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->user, $this->pass);
        }
        catch (PDOException $e) {
            die($e->getMessage());
        }
        return $this->DBH;
    }
}

user.php

date_default_timezone_set('America/Sao_Paulo');
include 'database.php';
class User extends Database {

    private $name;
    private $email;
    private $date;

    function __construct($name, $email) {
        $this->$name = $name;
        $this->$email = $email;
    }

    public function insert() {
        $STH = $this->DBH->prepare("INSERT INTO `phppdo` VALUES(NULL, :username, :email, UNIX_TIMESTAMP())");
        $STH->execute(array(
            ':name' => $name,
            ':emal' => $email,
        ));
    }
}

if(isset($_POST['submit'])) {
    $x = new User($_POST['name'], $_POST['email']);
    $x->insert();
}

脚本不工作!我得到Call to a member function prepare() on a non-object on line 16 = $STH = $this->DBH->prepare("INSERT INTOphppdoVALUES(NULL, :username, :email, UNIX_TIMESTAMP())");

我不知道为什么会这样……你能帮帮我吗?谢谢!!

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    使您的用户类如下所示:

    class User extends Database {
    
    private $name;
    private $email;
    private $date;
    
    function __construct($name, $email) {
    
        $this->name = $name;
        $this->email = $email;
        parent::__construct();
    }
    
    public function insert() {
    
        $STH = $this->DBH->prepare("INSERT INTO `phppdo` VALUES(NULL, :name, :email, UNIX_TIMESTAMP())");
        $STH->execute(array(
            ':name' => $this->name,
            ':email' => $this->email,
        ));
    }
    }
    

    【讨论】:

    • 嘿先生,它正在工作!但是还是在数据库中插入两次,你知道发生了什么吗?
    • 我正在使用你的代码和database.php,我已经在这个线程中写过。仅此而已!
    • 你能分享你的.sql吗?
    • CREATE TABLE phppdo ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(100) NOT NULL, email varchar(100) NOT NULL, date varchar(100) NOT NULL, PRIMARY KEY (id) )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2014-09-04
    • 2013-08-21
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多