PHP 用户注册

致命错误:未捕获错误:在 X:\x\x\x\class\auth.php:29 中的 null 上调用成员函数prepare() 堆栈跟踪:#0 x:\x\x\index.php(8 ): Auth->register_user() #1 {main} 在第 29 行的 x:\x\x\x\class\auth.php 中抛出

这是数据库连接文件

class getDB {

    protected $conn;


    public $db_host = 'localhost';

    public $db_user = 'root';

    public $db_pass = '';

    public $db_name = 'f_base';


    public function getConn() {

        try {

            $this->conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);


            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        } catch ( PDOException $e ) {

            die ('<h1>ERROR:</h1><h2>'.$e->getMessage().'</h2>');

        }

    }

    // TODO: Dodati funkcije koje ce moci da ucitaju databazu da bi se prikazalo nesto iz databaze 

}

该类用于注册


class Auth {


    public function __construct () {

        $connection = new getDB();

        $this->conn = $connection->getConn();


        return $this->conn;

    }



    public function register_user ( $username, $email, $password, $r_date ) {

        $reg_user = $this->conn->prepare("INSERT INTO korisnici ( username, email, password, r_date ) VALUES ( ?, ?, ?, ? )"); // THIS IS LINE I AM GETTING ERROR

        $reg_user->execute( array( $username, $email, $password, $r_date ) );        

    }

}

我收到错误的这一行


 $reg_user = $this->conn->prepare("INSERT INTO korisnici ( username, email, password, r_date ) VALUES ( ?, ?, ?, ? )"); // THIS IS LINE I AM GETTING ERROR


FFIVE
浏览 128回答 1
1回答

米琪卡哇伊

你犯了一个简单而常见的错误。检查类getDB方法getConn() - 您没有返回任何导致错误消息“prepare() on null”的内容。您正在尝试在Auth类构造中获取 PDO 连接对象 $this->conn = $connection->getConn();只需像这样添加回报class getDB {protected $conn;public $db_host = 'localhost';public $db_user = 'root';public $db_pass = '';public $db_name = 'f_base';public function getConn() {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; $this->conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);&nbsp; &nbsp; &nbsp; &nbsp; $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp; &nbsp; &nbsp; &nbsp; $this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);&nbsp; &nbsp; } catch ( PDOException $e ) {&nbsp; &nbsp; &nbsp; &nbsp; die ('<h1>ERROR:</h1><h2>'.$e->getMessage().'</h2>');&nbsp; &nbsp; }&nbsp; &nbsp; return $this->conn;}// TODO: Dodati funkcije koje ce moci da ucitaju databazu da bi se prikazalo nesto iz databaze&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP