Get the App
SLTechnology News&Howtos  ›  Database  › 

MongoDB combined with PHP

Shulou Source: shulou.com Published: 2022-06-01 15:23:36 10月24日 Update

A previous article introduced the installation and use of MongoDB: http://msiyuetian.blog.51cto.com/8637744/1720559

The following article mainly introduces how to connect PHP to MongoDB. Install PHP before testing. I do the test based on LAMP environment here.

1. Download and install the mongo extension of php

[root@centos ~] # cd / usr/local/src/

[root@centos src] # wget http://pecl.php.net/get/mongo-1.4.5.tgz-O mong_php.tar.gz

[root@centos src] # tar-zxvf mong_php.tar.gz

[root@centos src] # cd mongo-1.4.5/

[root@centos mongo-1.4.5] # / usr/local/php/bin/phpize

Configuring for:

PHP Api Version: 20090626

Zend Module Api No: 20090626

Zend Extension Api No: 220090626

Note: if some files are missing in this step, there is something wrong with the expansion package. You need to download an available expansion package online again.

[root@centos mongo-1.4.5] #. / configure-with-php-config=/usr/local/php/bin/php-config

[root@centos mongo-1.4.5] # make

[root@centos mongo-1.4.5] # make install

Installing shared extensions: / usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/

You can see the generated mongo.so file on the

[root@centos mongo-1.4.5] # ls / usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/

Mongo.so

2. Edit the configuration file

[root@centos mongo-1.4.5] # vim / usr/local/php/etc/php.ini / / add the last line

Extension = mongo.so

[root@centos mongo-1.4.5] # / usr/local/php/bin/php-m | grep mongo

Mongo

It can be seen from the above that the mongo extension has been loaded successfully

Restart the Apache service (if LNMP, restart the php-fpm service)

[root@centos mongo-1.4.5] # / usr/local/apache2/bin/apachectl restart

3. Testing

Create a new test file

[root@centos mongo-1.4.5] # vim / usr/local/apache2/htdocs/mongotest.php

The test results are as follows

[root@centos mongo-1.4.5] # curl localhost/mongotest.php

Connection to database successfullyDatabase mydb selected

From above, we can see that the configuration is successful.

Note: if we comment out the line "extension = mongo.so" in the / usr/local/php/etc/php.ini configuration file, the test result will be 500 after restarting the Apache service

[root@centos mongo-1.4.5] # curl localhost/mongotest.php-I

HTTP/1.0 500 Internal Server Error

Date: Sat, 09 Jan 2016 16:18:20 GMT

Server: Apache/2.2.31 (Unix) PHP/5.3.27

X-Powered-By: PHP/5.3.27

Connection: close

Content-Type: text/html

Tags: File test service configuration success article result one line data database comment environment problem first generate experiment select Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia Apple Redmi Xiaomi