gpt4 book ai didi

php - fatal error : Cannot use object of type MongoCursor as array

转载 作者:行者123 更新时间:2023-12-03 08:00:24 27 4
gpt4 key购买 nike

我将MongoDB与php结合使用-我试图获取使用用户名和密码登录的用户的ID,并将其存储为 session 变量。

我一直收到此错误,但我不明白为什么。

<?php
session_start();

$dbhost = 'localhost';
$dbname = 'story';

$mongo = new MongoClient("mongodb://$dbhost");
$db = $mongo->$dbname;

$collection = $db->users;

$email=$_POST['email'];
$password=$_POST['password'];

$user = $collection->find(array("email" => $email, "password" => $password));
$user->limit(1);
if ($user->count(true) > 0){
$_SESSION['user']['userid']=iterator_to_array($user['_id']->{'$id'});
header("Location:../webpages/master.php?page=home");
}else{
echo "Wrong username or password";
}

?>

最佳答案

find()返回一个游标,您可以在其上进行迭代以检索结果。

如果是单文档检索,请使用findOne()

$user = $collection->findOne(array("email" => $email, "password" => $password));

而且您不需要使用以下行:
$user->limit(1); // Don't use limit() with findOne()

关于php - fatal error : Cannot use object of type MongoCursor as array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052530/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com