PHP and MongoDB Connection

2021.01.04 14:55

졸리운_곰 조회 수:62

PHP and MongoDB Connection

xampp windows : mongodb php driver : php_mongodb-1.9.0-7.4-ts-vc15-x64.zip

Introduction

If you’re using PHP to build applications, you may want to interact with a MongoDB database in your code. Fortunately, it’s easy to connect to a MongoDB database from a PHP script with just a bit of setup and configuration. In this article, we’ll show you how to set up a PHP and MongoDB connection so that you can access a MongoDB database in your apps.

Prerequisites

Before attempting to set up a connection between PHP and MongoDB, a few essential prerequisites need to be in place:

  • You’ll need to make sure that either XAMPP or WAMP is already installed and configured on your system.

  • MongoDB must be installed and configured on your machine.

  • You’ll need to have internet access for downloading some required files.

Install MongoDB PHP Driver

In this section, we’ll start the process of setting up a PHP and MongoDB connection by installing the MongoDB PHP driver on our system. To do this, we simply download the needed ‘DLL’ (Dynamic Link Library) file that can be found at this link: MongoDB PHP.

We’ll put this downloaded file in one of our PHP installation directories, which we’ll discuss in the next section.

Configure PHP and MongoDB in Windows

Next, let’s review how to configure PHP in a way that will allow a connection to MongoDB in a Windows environment.

  • First, we open the php.ini file found in the following XAMPP directory:C:\xampp\php

  • Next, we add the following text in the extensions section of the file: extension=php_mongodb.dll

  • Finally, we extract the ‘DLL’ file that we downloaded earlier into the following directory: C:\xampp\php\ext

alt text

Creating a MongoDB Sample Database

Our next step will be to create a sample dataset that we can use in this tutorial.

First, we’ll connect to a database named productdb.

1
use productdb

Then we can perform an insertMany() operation to add some dummy documents that we can use for demo purposes. The operation will create the products collection and add these documents to it at the same time:

1
2
3
4
5
6
7
8
   db.products.insertMany( [
      { item: "keyboard", qty: 20 },
      { item: "mouse", qty: 40 },
      { item: "power supply" , qty: 30 },
      { item: "cpu" , qty: 30 },
      { item: "video card" , qty: 20 },
      { item: "memory module" , qty: 30 }
   ] );

This operation will return a response that looks like the following:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
http://s1004games.com

1
2
3
4
5
6
7
8
9
10
11
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5e48b471389f0fd56b8b0554"),
                ObjectId("5e48b471389f0fd56b8b0555"),
                ObjectId("5e48b471389f0fd56b8b0556"),
                ObjectId("5e48b471389f0fd56b8b0557"),
                ObjectId("5e48b471389f0fd56b8b0558"),
                ObjectId("5e48b471389f0fd56b8b0559")
        ]
}

We can verify that the products collection was successfully created using this command: db.products.find().pretty();

We should get results that look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0554"),
        "item" : "keyboard",
        "qty" : 20
}
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0555"),
        "item" : "mouse",
        "qty" : 40
}
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0556"),
        "item" : "power supply",
        "qty" : 30
}
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0557"),
        "item" : "cpu",
        "qty" : 30
}
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0558"),
        "item" : "video card",
        "qty" : 20
}
{
        "_id" : ObjectId("5e48b471389f0fd56b8b0559"),
        "item" : "memory module",
        "qty" : 30
}

Connecting to MongoDB Database

In this section, we’ll create a simple PHP script that will connect to our productdb database.

Let’s start by creating a new directory named ‘phpmongo’ in the htdocs directory. We can then create a new PHP file called ‘test.php’ and add the following code to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $qry = new MongoDB\Driver\Query([]);
     
    $rows = $mng->executeQuery("productdb.products", $qry);
   
    foreach ($rows as $row) {
   
         foreach ($rows as $row) {
        echo nl2br("$row->item : $row->qty\n");
    }

    }
   
?>

The code shown above will read data from the ‘products’ collection that exists within the ‘productdb’ database. Let’s take a closer look at what’s happening in this script:

  • We use $qry = new MongoDB\Driver\Query([]); to create a MongoDB query object with an empty array. This tells MongoDB to read all possible data within the target collection.

  • We then execute the query against the specified collection name using the following line of code: $rows = $mng->executeQuery("productdb.products", $qry);

  • Finally, we iterate over all matched documents and print it out on the page.

The result should look like the following:

Conclusion

When you’re writing PHP code and need to interact with a database, MongoDB is a natural choice. Fortunately, it only takes a few simple steps to create a connection between PHP and MongoDB. In this article, we walked you through the complete process of creating a PHP and MongoDB connection, and we provided a code example that includes a typical MongoDB query. With these instructions and code examples to guide you, you’ll be able to write PHP code that can query your own MongoDB database.

 

[출처] https://kb.objectrocket.com/mongo-db/php-and-mongodb-connection-1295

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
142 [php] [xampp] [php] php의 mail() 함수로 구글 이메일 보내기 / XAMPP 서버 및 aws의 EC2 / php mail function to send Gmail at XAMPP and AWS EC2 not working / Username and Password not accepted. file 졸리운_곰 2023.09.12 1
141 [php] PHP / MariaDB / 데이터베이스 값 가져와서 출력하기 졸리운_곰 2023.06.22 2
140 [php] Start Using HTML5 WebSockets Today With a PHP Server 지금 PHP 서버에서 HTML5 WebSocket 사용 시작 졸리운_곰 2023.05.09 0
139 [php] json_encode 유니코드 한글 깨짐 해결방법 졸리운_곰 2023.02.04 3
138 PHP 카운터 만들기-[1] 졸리운_곰 2022.07.20 12
137 PHP로 카운터 만들기 졸리운_곰 2022.07.20 11
136 How To Build A Rest API Using PHP file 졸리운_곰 2022.07.15 12
135 PHP REST API Authentication Using JWT file 졸리운_곰 2022.07.15 11
134 [PHP] JWT 구현하기 졸리운_곰 2022.07.15 556
133 [php] Coppermine PHP로 제작된 "웹 갤러리" 프로그램임. 상당히 잘 만들어진 것같아 졸리운_곰 2021.07.04 31
132 [php] imagick php 7.3 windows 설치하기 졸리운_곰 2021.07.04 36
131 [php] simple Rest API : Build a Simple REST API in PHP file 졸리운_곰 2021.05.31 16
130 [php][php 수학][php 수치해석] MathPHP - Powerful Modern Math Library for PHP file 졸리운_곰 2021.05.03 16
129 [Redis] php 세션 저장소를 redis 로 바꾸어 본 후기. file 졸리운_곰 2021.04.11 42
128 Creating a Website Design Templating System Using PHP 졸리운_곰 2021.02.13 22
127 Build a CRUD Operation using PHP & MongoBD 졸리운_곰 2021.01.04 23
126 CRUD Operation using PHP & Mongodb file 졸리운_곰 2021.01.04 26
» PHP and MongoDB Connection file 졸리운_곰 2021.01.04 62
124 PHP 기반의 Micro Frameworks 정리 졸리운_곰 2020.12.02 39
123 CKEditor 4 설치와 PHP 연동 하기 file 졸리운_곰 2020.11.22 46
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED