2012-03-22 93 views
3

所以,我有一個名爲'會員'的集合,並且我有我的每個'成員'的用戶名和密碼。 我需要知道的是我怎麼檢查,看看兩者是否匹配,即用戶名+密碼=成功簡單的PHP mongoDB用戶名和密碼檢查網站

這是我曾嘗試並正確進行搜索,只是它沒有返回錯誤,如果沒有用戶

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

事情是這樣的:

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

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

或者:

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

感謝芽,我怎麼什麼限制返回得到,我只想有_id數量和@RussellHarrower你可以使用'findOne'或'limit'姓氏和名字 – RussellHarrower 2012-03-22 21:49:56

+0

。檢查更新。 – Ben 2012-03-22 22:01:30

4

假設一個用戶名/密碼組合是唯一的,你可以使用一個findOne

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

如果你想限制回來某些字段中的數據,你可以在findOne結束指定它們:

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

@RussellHarrower僅供參考,我做了一個編輯,以幫助您找回_id,名和姓。 – Aaron 2012-03-23 13:58:54