How to read the database from an external PHP?

Hello,

Since days, we are trying to read our mango DB from an external PHP, hosted by a simple web provider. We need this in order to make a ladder for our guild.

We first tried to make Heroku to use our external MySQL database, but without success, so we used a MangoDB, but now we don’t know how to read it from our website.

I hope someone will help us, we really need…
Thank you and sorry for my english.

You need to install the drivers and connect using a URI for your target MongoDB. See https://docs.mongodb.com/drivers/php

Are you using a platform (e.g. WordPress) or a framework (e.g. Symfony)? Do you block on a specific step (e.g. Connection)? More information we’ll have, more easily we could help you.

Hello, we now installed the drivers + node.js, we are look at your link.
Yes we use Joomla.

Actualy I use
<?php

$client = new MongoDB\Client(
    'mongodb+srv://x:x@x.x.mongodb.net/x?retryWrites=true&w=majority'
);

$db = $client->test;
	?>

To connect on our db, with a VPS with node.js and the mango’s driver. But I don’t know how to read the content and show it on tables, I’m noob with db.

Here’s a PHP code to help you. Note: nested fields are not supported.

<?php
// Define some useful constants.
define('MONGO_URL', 'mongodb+srv://x:x@x.x.mongodb.net/x?retryWrites=true&w=majority');
define('MONGO_DATABASE', 'testdb');
define('MONGO_COLLECTION', 'testcoll');

try {

    // Connect to database and select collection.
    $mongoClient = new MongoDB\Client(MONGO_URL);
    $mongoCollection = $mongoClient->selectCollection(MONGO_DATABASE, MONGO_COLLECTION);
    
    // Get collection contents and store it.
    $mongoDocuments = $mongoCollection->find();
    $mongoDocumentsArray = $mongoDocuments->toArray();

} catch (\Throwable $th) {
    echo 'Error: ' . $th->getMessage();
}

// If collection is not empty:
if ( isset($mongoDocumentsArray) && count($mongoDocumentsArray) >= 1 ) {

    $mongoDocumentsArrayKeys = array_keys((array) $mongoDocumentsArray[0]);

    $htmlTable = '<table>';

    // Prepare table head.
    $htmlTable .= '<tr>';
    foreach ($mongoDocumentsArrayKeys as $mongoDocumentsArrayKey) {
        $htmlTable .= '<th>' . $mongoDocumentsArrayKey . '</th>';
    }
    $htmlTable .= '</tr>';

    // Prepare table body.
    foreach ($mongoDocumentsArray as $mongoDocumentArray) {
        $htmlTable .= '<tr>';
        foreach ($mongoDocumentArray as $mongoDocumentArrayValue) {
            $htmlTable .= '<td>' . $mongoDocumentArrayValue . '</td>';
        }
        $htmlTable .= '</tr>';
    }

    $htmlTable .= '</table>';

    // Display table.
    echo $htmlTable;

}
?>
1 Like

Thank you!
But I think the php host need mangodb and librairies installed, and node.js, no ?

PHP host needs MongoDB extension and library installed.