Execution of PHP code regarding database access using MongoDB is not giving desired results

138

I am using WAMP server 64bit as well as MongoDB 64 bit in my Windows 7 machine. I have successfully configured MongoDB on WAMP server wherephp_info() page shows MongoDB Support Version 1.3.2RC1 enabled. But the problem is whenever I establish connection with MongoDB in PHP code the code runs but it does not reflect the changes in MongoDB console. Why is this so?

 <?php
 $connection = new MongoClient();
 //$db = $connection->sample;

 // select a collection:
 //$collection = $db->first;
 $collection = $connection->sample->test1;

 $doc = array(
 "name" => "MDB",
 "type" => "database",
 "count" => 2,
 "info" => (object)array( "x" => 203, "y" => 102),
 "versions" => array("0.9.7", "0.9.8", "0.9.9")
 );

 $collection->insert( $doc );

 echo "Inserted successfully....";

 $document = $collection->findOne();
 var_dump( $document );

 ?>

The above code retrieves the inserted document as it is on browser. But in mongo.exe console there is no data inserted. My default database is 'db'.

383

Answer

Solution:

My default database is 'db'

I think you may be confusing thedb shell variable and the current database, which defaults to "test" unless you specify it a database name argument to themongo command. Consider the following:

$ mongo
MongoDB shell version: 2.5.5
connecting to: test
> db
test
> ^C
bye

$ mongo foo
MongoDB shell version: 2.5.5
connecting to: foo
> db
foo
>

The client tells me that it has connected to the "test" database by default, and evaluating thedb variable reports its name as a string. If I connect again and specify "foo" as the command line argument, I see "foo" as the default database. Additionally, I can runuse <name> when I'm in the shell to switch between databases.

In the PHP script above, you're accessing the "sample" database and "test1" collection when you evaluate$connection->sample->test1.

People are also looking for solutions to the problem: How to pass user input value from a PHP page to HTML page using AJAX

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.