简体   繁体   中英

Simple PHP mongoDB Username and Password Check for site

So, I have a collection called: 'members' and in that I have a user name and password for each of my 'members'. What I need to know is how do I check to see if the two match ie username + password = success

This is what I have tried and it does the search correctly, just it's not returning the error if no 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);

    }   

Something like this:

$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;

Assuming that a username/password combination is unique, you could use a findOne :

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

If you want to limit the data coming back to certain fields, you can specify them on the end of the findOne:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM