dpbf62565 2018-10-20 03:33
浏览 70
已采纳

在非对象PHP PDO上调用成员函数prepare()

can you help me? I'm getting a little problems with my script.

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();
}

The script isn't working! I'm getting Call to a member function prepare() on a non-object on line 16 = $STH = $this->DBH->prepare("INSERT INTOphppdoVALUES(NULL, :username, :email, UNIX_TIMESTAMP())");

I don't know why it's happening... Can you help me? Thank you!!

  • 写回答

1条回答 默认 最新

  • dongliyan7318 2018-10-20 03:51
    关注

    Make your User class like below :

    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,
        ));
    }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理