2

I have this error when I try to use my php file

Fatal error: Cannot use object of type MongoCursor as array in

Part of my code :

<?php
try {
           $connection = new MongoClient();
           $database   = $connection->selectDB('test');
           $collection = $database->selectCollection('articles');
         } Catch(MongoException $e) {
           die("Failed to connect to database ".$e->getMessage());
}
         $cursor = $collection->find();

       ?>

<?php session_start();

?>

<html>

<p> test1 </p>

<p> test </p>



 <h3> Comment the photo </h3>

       <?php foreach($cursor['comments'] as $comment):

I think error is due to : - <?php foreach($cursor['comments'] as $comment): or $cursor = $collection->find();

4 Answers 4

2

Convert $cursor to Array:

$elements = $cursor->toArray();
Sign up to request clarification or add additional context in comments.

Comments

1
try this one it convert your mango cursor object to array($data). 
then you can access data you want.


$data = array();
while($cursor->hasNext())
            {
                $cursor->next();
                $temp = array();
                $temp = $cursor->current();
                array_push($data, $temp);
            }

var_dump($data);

3 Comments

it converts your mongo cursor output from find query to array. then you can access data in foreach.
I still have no comment that appears on the page but comments are in the database
hasNext() is not a function now.
0

Remove $cursor['comments'] and do a loop like this:

<?php
    foreach ($cursor as $comment) {
       ?>
     <p> <?php echo $comment['name']; ?>  </p>
<?php   
 }
 ?>

6 Comments

you are using $comment outside foreach loop ?
there is no comment appears on the page
null value is stored in article. Go to your mongodb console and edit your document.
I am starting with mongodb , what I should write on console ?
after update { "_id" : ObjectId("552a56fd0faaf2bd03b7acda"), "text" : "after update", "comment_name" : "Anis", "comment_email" : "[email protected]" }
|
-1

Command:

$cursor = $collection->find();

gives you an array ($cursor = $collection->findOne() - gives you one element).

If you want to loop over comments then you have to use:

foreach($cursor as $oneElement) {
    foreach($oneElement['comments'] as $comment) {
        //some code
    } 
}

1 Comment

#find is the one that returns a cursor, #findOne returns an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.