Question

I'm working on a login for an application (school work), and I'm learning how to use the mysqli class in a proper way. Below is two methods from my application that's used for checking whether the username and password that the user types in is correct (ie. exists in the db) or not.

My question is if this is a correct way of using bind_param, or if it even could be "overkill" to use it for this purpose? Could/should it maybe be done in another way?

From LoginModel.php

public function DoLogin($username, $password){

    $query = "SELECT * FROM Users WHERE username=? AND password=?"; 
    $stmt = $this->m_db->Prepare($query);

    $stmt->bind_param("ss", $username, $password);

    $ret = $this->m_db->CheckUser($stmt);

    return $ret;
}

From Database.php

public function CheckUser($stmt) {

    if ($stmt->execute() == false) {
        throw new \Exception($this->mysqli->error);
    }
    $ret = 0;

    // $field1 = id, $field2 = username, $field3 = password
    if ($stmt->bind_result($field1, $field2, $field3) == FALSE) {
        throw new \Exception($this->mysqli->error);
    }

    if ($stmt->fetch()) {
        return true;        // Match exists in db           
    } else {
        return false;       // Match doesn't exist in db
    }
}
Was it helpful?

Solution

No, it's not overkill. The purpose of bind_param is to allow the MySQLi engine to prepare the command against undesirable effects. Most commonly, it's aids in the prevention of SQL Injection type of attacks. You are using it just as you should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top