Fatal error: Call to undefined method Database::prepare()

前端 未结 3 1067
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 18:28

I have created a separate class for database and users.

Database.php

 class Database{

     private $db;


    public function __construct(){

  /***         


        
3条回答
  •  感动是毒
    2020-12-03 19:04

    add the method "getmyDB" to database file

    class Database
    
        {
        /* Properties */
        private $conn;
        private $dsn = 'mysql:dbname=test;host=127.0.0.1';
        private $user = 'root';
        private $password = '';
        /* Creates database connection */
        public
    
        function __construct()
            {
            try
                {
                $this->conn = new PDO($this->dsn, $this->user, $this->password);
                }
    
            catch(PDOException $e)
                {
                print "Error!: " . $e->getMessage() . "";
                die();
                }
    
            return $this->conn;
            }
    
        public function getmyDB()
            {
            if ($this->conn instanceof PDO)
                {
                return $this->conn;
                }
            }
        }
    

    and call it when you create the constructor in the file user.php

    include "database.php";
    
    class User
    
        {
        /* Properties */
        private $conn;
        /* Get database access */
        public
    
        function __construct()
            {
            $this->conn = new Database();
            $this->conn = $this->conn->getmyDB();
            }
    
        /* Login a user */
        public
    
        function login()
            {
            $stmt = $this->conn->prepare("SELECT username, usermail FROM user");
            if ($stmt->execute())
                {
                while ($rows = $stmt->fetch())
                    {
                    $fetch[] = $rows;
                    }
    
                return $fetch;
                }
              else
                {
                return false;
                }
            }
        }
    

    and finally add test.php file

    include "user.php";
    
    $user = new User();
    $list = $user->login();
    
     foreach($list as $test)
        {
        echo $test["username"];
        }
    

提交回复
热议问题