1
\$\begingroup\$

I'm working to implement an users management class inside an already existing project, so I wrote this simple code that will be called from a controller who is responsable to hash the password and will verify if all the required fields are correctly filled from the user. My doubt is on how i can improve the code, I'm thinking about including a mail verification and a simple way to manage the $_SESSION, but for now I'm focused on the basic functionality of the class.

class.php

class hatdb{

public function __construct(){

    if(is_null($this->db)){    
        $this->db = new PDO('mysql:host=localhost;dbname=hatdb','',''); 
        }
    } 
}   

class users extends hatdb{

public function createUser($email,$username,$password){

    $stmt = $this->db->prepare('INSERT INTO users (email,username,password) VALUES (?, ?, ? )');      
        if($stmt->execute(array($email,$username,$password))){
            echo 'Account successful created';     
        } else {
            echo 'Something was wrong during the registration process.';
            }  
}    

public function loginUser($username,$password){

$stmt = $this->db->prepare('SELECT email,username,password FROM users WHERE email = ? OR username = ?');
    $stmt->execute(array($username,$username));
        if($stmt->rowCount() > 0){
            $result = $stmt->fetch(PDO::FETCH_OBJ);
                if(password_verify($password, $result->password)){
                echo 'logged';
                } else {
                    echo 'wrong password';
                }
         } else {
           echo 'Username or email does not exist in the database.';
     }     
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Please indent your code according to formatting standards. they are really simple: each subordinate code block is indented by 4 spaces. \$\endgroup\$ – Your Common Sense May 30 '18 at 14:04
  • 1
    \$\begingroup\$ An obligatory link to my article on common mistakes in database classes, note issues 1, 2 and 10 which are directly related to your code. \$\endgroup\$ – Your Common Sense May 30 '18 at 14:09
  • \$\begingroup\$ @YourCommonSense ok,I will take a look to the article you've linked. \$\endgroup\$ – user9741470 May 30 '18 at 14:13
  • 1
    \$\begingroup\$ Also, a simpler way to implement loginUser, phpdelusions.net/pdo_examples/password_hash \$\endgroup\$ – Your Common Sense May 30 '18 at 14:47
  • 1
    \$\begingroup\$ It cannot be only one connection. in the every object that extends hatdb a NEW database connection is created. Also, this "tip" is not applicable to your case. When called in constructor, your $this->db is ALWAYS null, and thus such a condition just makes no sense. It always return false and a new db connection is created. \$\endgroup\$ – Your Common Sense May 30 '18 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.