Simple PHP mongoDB Username and Password Check Site

So, I have a collection called: "members" and I have a username and password for each of my "members". I need to know how to check if two matches match: username + password = success

This is what I tried and it does the search correctly, it just doesn't return an error unless the user

public function userlogin($data)
    {
        $this->data = $data;
        $collection = $this->db->members;
        // find everything in the collection
        $cursor = $collection->find(array("username"=>$this->data['username'], "password"=>$this->data['password']));

        $test = array();
            // iterate through the results
            while( $cursor->hasNext() ) {
                $test[] = ($cursor->getNext());
            }
        //Print Results 

        if($test == NULL)
        {
            print "Sorry we are not able to find you";
            die;
        }
        //print json_encode($test);

    }   

      

+3


source to share


2 answers


Something like that:

$mongo = new Mongo();
$db = $mongo->dbname;    

$user = $db->collection->findOne(array("username" => $username, "password" => $password));
if ($user->count() > 0)
    return $user;
return null;

      



Or:

$user = $db->collection->findOne(array("username" => $username, "password" => $password));
$user->limit(1);
if ($user->count(true) > 0)
    return $user;
return null;

      

+3


source


Assuming the username and password combination is unique, you can use findOne :

$mongoConn = new Mongo();
$database = $mongoConn->selectDB('myDatabase');
$collection = $database->selectCollection('members');
$user = $collection->findOne(array('username' => $username,'password' => $password));

      



If you want to restrict the return of data to specific fields, you can include them at the end of findOne:

$user = $collection->findOne(array('username' => $username,'password' => $password),array('_id','firstname','lastname'));

      

+4


source







All Articles