Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have created a separate class for database and users.

Database.php

 class Database{

     private $db;


    public function __construct(){

  /*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username_web';

/*** mysql password ***/
$password = 'password_web';



try {
    $this->db = new PDO("mysql:host=$hostname;dbname=kamadhenu_web", $username, $password);
    /*** echo a message saying we have connected ***/

       }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

 }

  /*** Query Function ***/
 public function query($sql)
        {
        return $this->db->query($sql);
        }



 }

Users.php

class Users{

     private $db;

public function __construct($database) {
$this->db = $database;

}


     public function login($username, $password)
     {

        $query=$this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
        $query->bindValue(1, $username);
        try{
        $query->execute();
        $data = $query->fetch();
        $stored_password = $data['password'];
        $id = $data['id'];
        #hashing the supplied password and comparing it with the stored hashed password.
        if($stored_password === sha1($password)){
        return $id; 
        }else{
        return false;   
        }

        }catch(PDOException $e){
        die($e->getMessage());
}

 }




 }

Here is my Login page with username and password.

 login.php

include('database.php');
include('users.php');

$dbh= new Database();
$users= new Users($dbh);


if (isset($_POST['submit']))

{ 

$username= $_POST['username'];
$password= $_POST['password'];

    $login = $users->login($username, $password);




        if ($login === false) {
        $errors[] = 'Sorry, that username/password is invalid';
        }
        else {
        // username/password is correct and the login method of the $users object returns the user's id, which is stored in $login.

        $_SESSION['id'] = $login; // The user's id is now set into the user's session in the form of $_SESSION['id']
        #Redirect the user to home.php.
        header('Location: list-updates.php');
        exit();
        }





}

When I execute I get an error:

Call to undefined method Database::prepare()

like image 486
user2460790 Avatar asked Oct 27 '13 18:10

user2460790


2 Answers

You create $dbh when you instantiate Database(), but instantiating the Database only returns an instance of your Database class, not your db connection. You should have a getDb to get your connection from database object:

$dbClass = new Database();
$dbh = $dbClass->getDb(); // here you get the connection
$users= new Users($dbh);  // here you give to Users() the $dbh, that isn't your 
                          // connection.. it's just Database class

Database construct only return an instance of your Database class, not your db connection

class Database{

 private $db;


public function __construct(){

    try {
     $this->db = new PDO("mysql:host=$hostname;dbname=kamadhenu_web", $username, $password);
    /*** echo a message saying we have connected ***/

   }
    catch(PDOException $e)
        {
            echo $e->getMessage();
       }    
 }

 public function getDb() {
       if ($this->db instanceof PDO) {
            return $this->db;
       }
 }


}
like image 119
Cristian Bitoi Avatar answered Oct 21 '22 14:10

Cristian Bitoi


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"];
    }
like image 32
Houssem Cherif Avatar answered Oct 21 '22 12:10

Houssem Cherif