所以,我有一个名为''members'的集合,我的每个'成员'都有一个用户名和密码。 我需要知道的是如何检查两者是否匹配,即用户名+密码=成功
这是我试过的,它正确搜索,如果没有用户,它就不会返回错误
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);
}
答案 0 :(得分: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'));
答案 1 :(得分: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;