0

I am trying to learn OOP, currently rewriting a use login. I keep getting an error saying:

Fatal error: Call to a member function prepare() on a non-object in /var/www/new.php on line 22

Can someone point out what I did wrong? Also does this look like good OOP coding practice so far besides the obvious bug?

<?php  
ini_set('display_errors', TRUE);
require 'resources/library/DB.php';

    class DataBase
    {
        private $conn = null;

        public function __construct($conn)
        {
            $this->conn = $conn;
        }

            public function setConn($conn)
        {
            $this->conn = $conn;
            return $this;
        }

       public function retrievePassword($userNAme) 
       {
       $stmt = $this->conn->prepare('SELECT `password` FROM `users` WHERE `userName`= :userName');
       $stmt->bindValue(':userName', $userNAme);
       $stmt->execute();
       $salt = $stmt->fetchColumn();

       return $salt;
}
        }
    $db = new DataBase($conn);
    echo $db->retrievePassword('testuser');

?>  
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – BlitZ Sep 21 '13 at 05:44
  • Looks like `$this->conn` is empty or undefined. – BlitZ Sep 21 '13 at 05:45

2 Answers2

3

Your constructor is incorrect.

The correct PHP constructor is

__construct.

Thus when you call new Database($pdo), it uses the default constructor - which does no assignment.

Zack Newsham
  • 2,810
  • 1
  • 23
  • 43
  • I am now getting `Warning: PDO::__construct() expects at least 1 parameter, 0 given in /var/www/new.php on line 30 Catchable fatal error: Argument 1 passed to DataBase::__construct() must be an instance of PDO, null given, called in /var/www/new.php on line 30 and defined in /var/www/new.php on line 9` – Yamaha32088 Sep 21 '13 at 05:49
  • what have you changed? You should have changed __constructor to __construct. Nothing should have changed with how you create a new Database. – Zack Newsham Sep 21 '13 at 05:51
  • Thats all I changed nothing else – Yamaha32088 Sep 21 '13 at 05:52
  • update your question with the exact code you are currently using please, lets see if we can figure it out. – Zack Newsham Sep 21 '13 at 05:53
  • @Yamaha32088 pass your connection string and user requisites to `new PDO()`. More information [here](http://www.php.net/manual/en/pdo.construct.php). – BlitZ Sep 21 '13 at 05:54
  • as @CORRUPT said, you have to pass a connection string to PDO constructor. You cant call new PDO(). – Zack Newsham Sep 21 '13 at 05:56
  • I was able to fix it by just removing `new PDO` – Yamaha32088 Sep 21 '13 at 06:01
0

You are not passing your $conn to retrievePassword().

So it probably does not know what conn is.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126