0

Here is the complete script:

connection.php

class Connection{
    public function dbConnect(){
    return new PDO("mysql:host=localhost; dbname=test", "root", "");        
    }   
}

user.php

include_once('connection.php');

class User{

  private $db;

  public function __constructor(){
    $this->db = new Connection();
    $this->db = $this->db->dbConnect();
  }

  public function Login($name, $pass){
    if(!empty($name) && !empty($pass)){
        $st = $this->db->prepare("SELECT * FROM users WHERE name =? and pass =?");
        $st->bindParam(1, $name);
        $st->bindParam(2, $pass);
        $st->execute();     

        if($st->rowCount() == 1){
            echo "User verified. Access granted";   
        }else{
            echo "Incorrect";   
        }

    }else{
        echo "Please enter name and password";  
    }
  }

}    

index.php

include_once('User.php');

if(isset($_POST['submit'])){
$name = $_POST['user'];
$pass = $_POST['pass'];

$object = new User();
$object->Login($name, $pass);   
}

But when I try it, this error appear:

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\testes\User.php on line 16

Line 16: $st = $this->db->prepare("SELECT * FROM users WHERE name =? and pass =?");

1 Answers1

2

Your magic is busted

public function __constructor(){

should be

public function __construct(){

  • Thanks a lot! Fixed. Only another question: how I introduced encripted passwords? –  Feb 06 '13 at 18:44
  • 1
    You can hash your password using a hash function, see http://php.net/manual/en/faq.passwords.php – bpoiss Feb 06 '13 at 18:49
  • I've used md5 to encrypt passwords. As this is my first time using PDO, I wonder if md5 + pdo is a solution to avoid sql injection. –  Feb 06 '13 at 18:58
  • 1
    PDO + prepared statements should be fine. MD5 does nothing to prevent SQL injection, it only makes sure that plain-text passwords cannot be stolen. However, MD5 is not very secure anymore; MD5 hashes of popular passwords have been collected. At *least* use a 'salt' for each password and consider using 'SHA' or even better bcrypt / blowfish (http://stackoverflow.com/questions/2235158/sha1-vs-md5-vs-sha256-which-to-use-for-a-php-login) – thaJeztah Feb 06 '13 at 19:13