3

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

2 Answers 2

4

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks bud, how do I limit what gets returned, I only want there _id number and first and last name
@RussellHarrower you could use findOne or limit. Check the update.
4

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

1 Comment

@RussellHarrower FYI, I made an edit to help you get back only _id, firstname and lastname.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.