Viewed   91 times

I am using PHP to connect with MongoDB. My code is as follows.

// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;

$customers = $db->customer->find();

i want to return $customers collection as json document to my HTML. How can i do this?

 Answers

2

You can do this two ways:

echo json_encode(iterator_to_array($customers));

or you can manually scroll through it:

foreach($customers as $k => $row){
    echo json_encode($row);
}

Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.

Wednesday, October 12, 2022
 
loopo
 
4

Is there a way (without manually logging into Mongo and running the command) and executing it via a PHP script without locking?

As you stated the best thing is to do it client side. As for the bandwidth, unless you got a pre-90's network then it will most likely be a very small amount of bandwidth in comparison to how much you would use for everything else including replica sets etc.

What you could do is warehouse your deletes upon their actual deletion (in your app) instead of once every day and then you would, once a day, go back through your original collection removing all deleted rows. That way the bandwidth will be spread throughout the day and when it comes to clean your production you just do a single delete command.

Another alternative would be to use an MR and make its output be that collection.

Though in general warehousing deletes in this manner is normally more work than it is worth. It is normally better to just keep them in your main collection and work your queries around the deleted flag (as you probably already do to not warehouse these immediately).

Tuesday, August 16, 2022
 
5

Add the below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>
Thursday, August 11, 2022
 
4

When you query something to MongoDB and you expect results, you will have this variable called cursor, which simply is a pointer to the document you currently did read. It is just like a scrollbar in the browser.

You can specify how many documents it should read into a buffer batchSize as you did with value 1.

It is useful when you know how much documents you expect to read. When you only need 10 documents, you can get all those in a single network packet using batchSize => 10. When specify batchSize => 5, it will take longer because it does take two network packets to the database to get the expected 10 documents.

You are safe using the default batchSize.

You can try to iterate over the cursor using foreach like in an example in the docs: http://php.net/manual/en/class.mongocommandcursor.php

Im not sure if the php.net documentation is up to date with the most current version of the MongoDB driver.

Sunday, November 13, 2022
 
3

Since you post does not mention a working PHP file, I will include it for the sake of completeness. This could be a long (long) post....

So, first. This is an example of a PHP file that is stored with the name my_test.php in at this location: c:wampwwwsome_folder_namemy_test.php (Please see the edit history for the code)

Now, let me explain the important portions of this PHP. These parameters should be configured to use your settings:

$DB_HOST = 'YOUR_IP_ADDRESS';
$DB_UNAME = 'MYSQL_USERNAME';
$DB_PWD = 'MYSQL_USER'S_PASSWORD';
$DB_DATABASE = 'DATABASE_NAME';

The IP Address should be either localhost or the IP address of the computer hosting the MySQL database. Preferably an IP address so you can test on physical devices. using localhost would work only on Virtual Devices.

Next up is adding the columns to an array that will construct a single record (row) in the JSON response. Take a look at this line for example:

$stuff["id"] = $row['id'];

The $stuff["id"] will basically become the tag in the resulting JSON Object whereas the $row['id'] is what indicates the column name from your DB's table. So the $row["...."] has to be identical to the column names in the DB table. While the $stuff["...."] can be just about anything. As long as it makes sense to you.

This line echo(json_encode($response)); will convert the response into a JSON format.

Now lets look at the Java code. First up in this is a class that will help you parse through the result. It was taken off a tutorial off a website (I don't remember which). Just copy an paste the following code in a Java class. No need to change anything in this file. Do give it a good read to understand how it works. I have it named JSONParser (Please see the edit history for the code):

Finally, how would to actually get the resulting JSON and parse it in an Activity / Fragment.

I parse the data in an AsyncTask, which is required anyway considering you will be performing a network operation. (Please see the edit history for the code)

Points to note in this Java:

  1. This String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php"; needs to have either an IP address such as 192.168.0.x or if you are testing on a virtual device, it should be 10.0.2.2. The earlier (192..) won't work on an emulator and the later (10.0...) won't work on a physical device.
  2. In this: String TAG_STUFF = "stuff";, the "stuff" corresponds with this from the PHP file: $response["stuff"] = array();. The TAG_STUFF should basically use whats in $response["stuff"].

Hope all the above makes sense. Comment if you need help. ;-)

UPDATED WITH WORKING SOLUTION:

This is very weird indeed. But, I have a working solution. When using the OP's code, the application indeed crashes. For lack of time to test why it crashes, I am instead posting a solution directly.

First, instead of keeping testing as an independent class, create it as an inner class back in the MainActivity.

class testing extends AsyncTask<Void, Void, Void>   {
....
}

Second, declare the variables globally (the jParser, URL_TO_PHP, etc), as against the current declarations before the onPreExecute(). See the complete solution below for clarity...

public class MainActivity extends Activity {

    JSONParser jParser;
    String URL_TO_PHP = "http://testbox.site50.net/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    ....

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                new testing().execute();
                break;
            default:
                break;
        }

    }

    private class testing extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... args) {

            /* Building Parameters */
            List<NameValuePair> params = new ArrayList<>();

            /* getting JSON string from URL */
            JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

            try {
                /* Checking for SUCCESS TAG */
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                    /** CHECK THE NUMBER OF RECORDS **/
                    int intStuff = JAStuff.length();

                    if (intStuff != 0) {

                        for (int i = 0; i < JAStuff.length(); i++) {
                            JSONObject JOStuff = JAStuff.getJSONObject(i);
                            Log.e("ALL THE STUFF", JOStuff.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
}

While testing, I also took a screengrab of the results. Here it is:

Again, because I am stretched a little thin at the moment, I won't be able to go find out what really is causing the crash in the OP's code. But it's intriguing enough to find out..

Tuesday, August 9, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :