|
| 1 | +.. _php-connect-to-mongodb: |
| 2 | + |
| 3 | +================== |
| 4 | +Connect to MongoDB |
| 5 | +================== |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: tutorial |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: test connection, runnable, code example |
| 13 | + |
| 14 | +After retrieving the connection string for your MongoDB Atlas deployment, |
| 15 | +you can connect to the deployment from your PHP application and query |
| 16 | +the Atlas sample datasets. |
| 17 | + |
| 18 | +.. procedure:: |
| 19 | + :style: connected |
| 20 | + |
| 21 | + .. step:: Edit your PHP application file |
| 22 | + |
| 23 | + Copy and paste the following code into the ``quickstart.php`` file, which queries |
| 24 | + the ``movies`` collection in the ``sample_mflix`` database: |
| 25 | + |
| 26 | + .. literalinclude:: /includes/get-started/quickstart.php |
| 27 | + :language: php |
| 28 | + :dedent: |
| 29 | + |
| 30 | + .. step:: Assign the connection string |
| 31 | + |
| 32 | + Replace the ``<connection string>`` placeholder with the |
| 33 | + connection string that you copied from the :ref:`php-connection-string` |
| 34 | + step of this guide. |
| 35 | + |
| 36 | + .. step:: Run your PHP application |
| 37 | + |
| 38 | + In your project directory, run the following shell command to start the application: |
| 39 | + |
| 40 | + .. code-block:: bash |
| 41 | + |
| 42 | + php quickstart.php |
| 43 | + |
| 44 | + The command line output contains details about the retrieved movie |
| 45 | + document: |
| 46 | + |
| 47 | + .. code-block:: none |
| 48 | + :copyable: false |
| 49 | + |
| 50 | + { |
| 51 | + "_id": { |
| 52 | + "$oid": "..." |
| 53 | + }, |
| 54 | + ... |
| 55 | + "rated": "R", |
| 56 | + "metacritic": 80, |
| 57 | + "title": "The Shawshank Redemption", |
| 58 | + ... |
| 59 | + } |
| 60 | + |
| 61 | + If you encounter an error or see no output, ensure that you specified the |
| 62 | + proper connection string in the ``quickstart.php`` file and that you loaded the |
| 63 | + sample data. |
| 64 | + |
| 65 | +After you complete these steps, you have a PHP application that |
| 66 | +connects to your MongoDB deployment, runs a query on the sample |
| 67 | +data, and returns a matching document. |
| 68 | + |
| 69 | +.. include:: /includes/get-started/troubleshoot.rst |
0 commit comments