Simple PHP mongoDB Username and Password Check for site

情到浓时终转凉″ 提交于 2019-12-23 18:24:11

问题


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 i.e. 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);

    }   

回答1:


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;



回答2:


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'));


来源:https://stackoverflow.com/questions/9830735/simple-php-mongodb-username-and-password-check-for-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!