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

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,