Tech blog for programming articles and video tutorialshttp://programmerblog.net
Tue, 15 Aug 2017 18:11:37 +0000en-UShourly1https://wordpress.org/?v=4.8.1using socketio with nodejs – create a chat applicationhttp://programmerblog.net/using-socketio-with-nodejs/
http://programmerblog.net/using-socketio-with-nodejs/#respondSun, 30 Jul 2017 20:48:09 +0000http://programmerblog.net/?p=1219Last updated:30th July, 2017Using socketio with nodejs Real time communication is an important feature in today’s web applications. Different technologies like long polling and socket.io are used for this purpose. Socket.io makes real time communication very easy and efficient. Socket.io can perform two way data communication. This tutorial gives you a detailed insight on using …

Using socketio with nodejs

Real time communication is an important feature in today’s web applications. Different technologies like long polling and socket.io are used for this purpose. Socket.io makes real time communication very easy and efficient. Socket.io can perform two way data communication. This tutorial gives you a detailed insight on using socketio with nodejs and creating a simple chat application.

In this application following tasks are performed for using socketio with nodejs.

1. Create a nodejs, express application

2. Install socket.io module for real time communication on client and server

This command changes directory to project folder and install all necessary modules in node_modules folder. To run this app type

SET DEBUG = using-socketio-with-nodejs:* & npm start

This command starts nodejs server on port 3000. Open browser and type URL.

http://localhost:3000

You can view running app.

When ever you make changes in a JS files in routes folder remember to stop server using ctrl + c and start the server again so changes can effect.

Install socket.io module

Let us first install socket.io. Stop the app on command line by pressing ctrl+c.

npm inatall socket.io

Using socketio with nodejs

For using socketio with nodejs, first need to understand emit and receive events.

Emit and Receive events

Default events for socket.io are connect, message and disconnect but custom events can also be emitted or received. Server or client can emit and receive events. When server emits an event, it is emitted to all connected clients. Suppose server emits an event send announcement.

io.emit('send announcement');

Similarly a client can also emit an event to server with some data. So to send and event from server to client or from client to server, emit method is used.

io.emit('new message', {message : 'Hello'});

Client emits an event new message and also a message Hello. If you want a client or server to act upon or respond to an event, implement .on method.

socket.on('send announcement', function () {
.... do stuff here
});

Likewise if a client emits an event and server receives that event using .on method as follows.

In the code above first we included socket.io module that is installed using npm. This module is assigned to socket_io variable. Next socket_io() method is a called and is assigned to io variable. A socket object is created and io is attached to a socket via socket.io.

socket’s join event

When join event is emitted from client and is received by server, a user object is passed from server. That contains user name. User name is accessed via user.username and is also assigned to socket.username.

Each username is added to user’s array that is used to keep track of users those are connected to the chat. Lastly in this event Server emits a user joined event to all connected clients and sends back username and all users’s array.

In this tutorial usernames are stored in an array that is initialize every time a user joins chat. It should be stores in a database or session so we can persist the connected usernames and messages.

User is typing event on server side

On client side when a user types a message in chat text box, other users are notified that some user is typing. To accomplish this task client emits a typing event that we receive in server side.

From client a msg object is receive and server emits a typing event to all connected users with an object containing message and a username.

Receive message from client and send to connected clients

When a connected client types a message and clicks Send button, message is sent to server. Other users can also see message. Emitted event is received in an event called new message. Username and message is received and is emitted to all connected clients.

User disconnect event

When a user disconnects or closes browser, server receives a disconnect event. Server emits a disconnect event and let all clients know that a user is disconnected and removes username from user’s array.

Socket.io client side code

Add client side code for using socketio with nodejs.

Add code in layout.pug

Open layout.pug in views folder. First add bootstarp.css and then style.css. After body and blockcontent, add socket.io library. After this jQuery and a custom JavaScript file chat_scrtip.js is included.

First include socket.io module and assign it to socket variable. No database or HTML form is used to get or save username. For demo purposes, an alphanumeric username of 6 characters is randomly generated. Username is assigned to username variable.

Emit user join event and receive user joined event

Whenever a user visits chat application, join event is emitted to server. Username is sent to server. Server receives event as described above with username. Then username and users list is sent to all connected clients by server, emitting user joined event.

[username] joined chat room message is shown in a div with class .js-userjoined. Another div displays connected userslist. A span for each user is added. Id of each span is a username.

User disconnected event

When a user closes browser or ends chat session, Server receives a Disconnect event. Server emits a user disconnected event to all connected clients with disconnected username. span of this username is removed from div.

Receiving user’s messages using socketio with nodejs

When a user sends a message to server. Server receives message from user with username and emits the message and username to all connected users. Client on the other hand, receive an event chat message. In call back function client receives data from server.

Data object contains username and message. Username and message is concatenated in a string and is appended to messages div. Messages are displayed to user.

Sending user message to server using socketio with nodejs

User message is sent to server, when a user types a message in the message box and clicks Send button.

$(function () {
.....
});

In JavaScript file jQuery ready function is defined. Functions are declared to send messages and show user typing status to all other connected users. When send button is clicked, message from txtmessage text box is assigned to message variable. new_message event is emitted to server with username and a message.

User is typing event

To show all users a message that user is typing. keyup event of text box is called. When user presses a key while typing a message, typing variable is set to true; then typing event is emitted to server with a message that says typing …. and username.

After that cleartimeout method is called. Lastly timeout method is defined. This method is called every 2 seconds and emits an typing event.

User is typing implementation in using socketio with nodejs

Now to implement user is typing feature on client side, receives typing event from server. Client checks if username and message exists. HTML with username and message is assigned to a div with .typing class. Otherwise blank div is displayed. Lastly a timeout method is implemented.

Running chat application

Now finally to run this app, go to project folder on command line. Type following command.

node bin/www

Open browser and in address bar type following URL.

http://localhost:3000

Summary

To summarize, in this tutorial you have created a real time chat application using socketio using nodejs. Implemented send and received message feature, informed other user when a user joins chat room with users list. User is typing functionality is also implemented.

You can download source code of this tutorial by clicking download link. Please leave your feedback and comments. Follow us on twitter to get updates on latest articles.

]]>http://programmerblog.net/using-socketio-with-nodejs/feed/0How to generate pdf using nodejs, express and mysql with pdfkithttp://programmerblog.net/generate-pdf-using-nodejs/
http://programmerblog.net/generate-pdf-using-nodejs/#respondMon, 17 Jul 2017 18:57:27 +0000http://programmerblog.net/?p=1173Last updated:17th July, 2017Generate pdf using nodejs In dynamic web applications developers often need to export data in pdf, csv, rss or xml formats. NodeJS have many libraries and modules that are used to produce such kind of output. A previous tutorial explored how to zip and unzip files using nodejs. In this tutorial you are going …

Generate pdf using nodejs

In dynamic web applications developers often need to export data in pdf, csv, rss or xml formats. NodeJS have many libraries and modules that are used to produce such kind of output. A previous tutorial explored how tozip and unzip files using nodejs. In this tutorial you are going to learn how to generate pdf using nodejs, express and mysql. pdfkit module is usedto generate pdf and node orm is used to connect to database and fetch records.

Following tasks are going to be performed in this tutorial.

1. Create a MySQL database and table for news posts

2. Generate an express application

3. Install pdfkit and orm modules using NPM

4. Display records from database using node orm module

5. Using pdfkit module to generate pdf using nodejs

Create a News MySQL database

First you need to create a MySQL database and a table for news posts using PhpMyAdmin. To install PhpMyAdmin, download WAMP or XAMPP and install on your system. After installation open PhpMyAdmin and click SQL tab. Execute queries given below.

Sample news posts from BBC and Tech News World site are inserted in to database.

CREATE DATABASE IF NOT EXISTS dbnews DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE dbnews;
--
-- Table structure for table tbl_posts
--
CREATE TABLE tbl_posts (
id int(11) NOT NULL,
title varchar(500) NOT NULL,
detail text NOT NULL,
publish_date datetime NOT NULL,
author_name varchar(200) NOT NULL,
link varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table tbl_posts
--
INSERT INTO tbl_posts (id, title, detail, publish_date, author_name, link) VALUES
(1, 'Raspberry Pi scores UK\'s top engineering award', 'The team behind the device was awarded the Royal Academy of Engineering\'s MacRobert Prize at a ceremony in London last night.\r\n\r\nThe tiny computer launched in 2012. Its designers hoped to introduce children to coding and had modest ambitions.\r\n\r\nThey beat two other finalists, cyber-security company Darktrace and radiotherapy pioneers Vision RT, to win the prize.\r\n\r\nPrevious winners of the innovation award, which has been run since 1969, include the creators of the CT (computerised tomography) scanner; the designers of the Severn Bridge; and the team at Microsoft in Cambridge that developed the Kinect motion sensor.\r\nExceeded expectations\r\n\r\nA tiny cheap computer that might encourage youngsters to learn programming was the idea of a small team of scientists and Cambridge University academics.\r\n\r\nThey hoped to sell a few thousand units, but sales have now passed 14 million, and the Pi is widely used in factories as well as in classrooms and homes.\r\n\r\nOne of the MacRobert award judges, Dr Frances Saunders, said a small engineering team had redefined home computing.', '2017-07-02 00:00:00', 'BBC News', 'http://www.bbc.com/news/technology-40444356'),
(2, 'Future Energy: China leads world in solar power production', 'Ten years ago, Geof Moser had just graduated with a master\'s degree in solar energy from Arizona State University - but he didn\'t feel much opportunity lay at his feet in his home country.\r\n\r\nSo he headed for China.\r\n\r\n\"The solar industry was fairly small and there weren\'t a lot of jobs,\" he remembers. \"Just a few for installation.\" But the Chinese government had big ambitions to expand solar and Moser saw his chance.\r\n\r\nHe spent some years accumulating knowledge about the Chinese solar industry, before co-founding Symtech Solar, which designs solar panel systems using Chinese parts.\r\nMarket access\r\n\r\nThe idea is to make it easy for organisations outside China to access components without the hassle of having to source and assemble lots of different parts. ', '2017-07-02 00:00:00', 'BBC News', 'http://www.bbc.com/news/business-40341833'),
(3, 'Securing Your Linux System Bit by Bit', 'As daunting as securing your Linux system might seem, one thing to remember is that every extra step makes a difference. It\'s almost always better to make a modest stride than let uncertainty keep you from starting. Fortunately, there are a few basic techniques that greatly benefit users at all levels, and knowing how to securely wipe your hard drive in Linux is one of them.', '2017-07-02 00:00:00', 'Tech World', 'http://www.technewsworld.com/story/Securing-Your-Linux-System-Bit-by-Bit-84607.html');
--
-- Indexes for table tbl_posts
--
ALTER TABLE tbl_posts
ADD PRIMARY KEY (id);
--
-- AUTO_INCREMENT for table tbl_posts
--
ALTER TABLE tbl_posts
MODIFY id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;COMMIT;

Generate a NodeJS application

To generate pdf using nodejs, you need to generate a nodejs, express application using Express tool on command line. First install express generator. To installexpress generator, type following command on command line.

npm install express-generator -g

Express application to generate pdf using nodejs

Express tool is used to generate an express application skeleton. pug is used as template engine for view files.

express --view=pug generate-pdf-using-nodejs

After application is generated, install required modules using npminstall.

cd generate-pdf-using-nodejs && npm install

To run the application, type

Set debug = generate-pdf-using-nodejs:* &npm start

or

node bin/www

To view application in browser, open browser and type URL

http://localhost:3000

By default nodejs application runs on port 3000. You can stop a nodejs application by pressing ctrl+c on command line.

Install node ORM and create news model

On command line type command below to install Node ORM module.

npm install orm

This command installs node orm. ORM is used to map database objects and perform database related tasks and queries easily.

In the code orm module is included and assigned to orm variable. Next router.use method is used and a model is created inside orm.express and connected to dbnews database. If there is a password on your system for database user, you can specify after username like username:password@localhost.

Inside function db object and a model is defined for tbl_posts and is assigned it to models.news. Table structure for tbl_posts with id, title, details, author name and publish date columns are assigned to model.

News model’s find method is used to find all records. You can see empty {} here. This is criteria, as no criteria is used in this method so all records are selected from database. In callback function, error and news are parameters are passed. News array is assigned to index view file.

In page above HTML table is displayed with table headings #,Title, Author and Action. Inside tbody section all news items are displayed in a loop. A link Generate PDF is addedagainst each record. Open browser and type this URL.

http://localhost:3000

Add /pdf route to generate pdf using nodejs

When a user clicks on Generate PDF link, /pdf route is executed. Id of the post is passed to route and database record is fetched from database using find method of news model. PDF is generated using pdfkit module, so first install pdfkit module. Open command line.

As you can see a new route ‘/pdf’ is created. Inside route req.query.id gets id parameter from URL query string. Next an object of pdfDocument is created.

News post id is passed to model.find method. In callback method the data of this new post is fetched and assigned to newspost array. Then title, detail, publish date, author name and link valuesare assigned to variables.

Generate PDF from database record

Title of news post is used as PDF file name and is assigned to filename variable. Headers are also set. Headers are used to pass any additional data to server or client. Here content type of file application/pdf ispassed to user’s browser.

Next font family with font size, x and y position are assigned to text for title of document. Under title link to original news is added with fill color as blue. After link author name is added with red fill color.

Detail of post is added to pdf document with fill color black and font size 15. Inside text property detail is assigned from database, alignment is justified with 30px indentation and a height with 300px. Lastly doc object contents are stream to response object. User is prompted to save the pdf file.

You can see a pdf generated above. To get more information about pdf options you can visit pdfkit site.

Summary

To summarize in this tutorial we have created a MySQL database to save news, installed ORM and pdfkit modules. Records from database are displayed. Clicking on GeneratePDF link of a news generates pdf file. Click here to download source code used in this tutorial.

Please leave your feedback and comments. Follow us on twitter to get information about upcoming tutorials.

]]>http://programmerblog.net/generate-pdf-using-nodejs/feed/0How to zip or unzip files using NodeJS and Express JS frameworkhttp://programmerblog.net/zip-or-unzip-files-using-nodejs-tutorial/
http://programmerblog.net/zip-or-unzip-files-using-nodejs-tutorial/#respondSat, 08 Jul 2017 11:51:04 +0000http://programmerblog.net/?p=1124Last updated:8th July, 2017How to zip or unzip files using NodeJS Compressing or uncompressing files is an important feature in a web application. Suppose you are working on a web application that needs to zip or unzip files using NodeJS. So this tutorial is going to explain how to zip or unzip files using NodeJS. In …

How to zip or unzip files using NodeJS

Compressing or uncompressing files is an important feature in a web application. Suppose you are working on a web application that needs to zip or unzip files using NodeJS. So this tutorial is going to explain how to zip or unzip files using NodeJS. In a previous tutorial we explored how to Zip, save and download files using codeigniter.

In this tutorial following tasks are going to be performed.

1. Create an application to zip or unzip files using NodeJS.

2. Install express-easy-zip module to compress files or directories

3. Install unzip NodeJS module to unzip a file

You can view the app below.

Create an application to zip or unzip file using NodeJS

If you have not installed NodeJS yet, then please visit NodeJS website, download and install NodeJS. To generate an Express and NodeJS application, you need to install. express generator tool

Installing express generator

Generate a NodeJS Express application

After express generator installation. Type following command on command line to generate a NodeJS, express application.

express --view=pug nodejs-zip-unzip-files

Here pug is used as template engine in view files. This command will generate an application named nodejs-zip-unzip-files. Next type cd nodejs-zip-unzip-files &&npm install command to install dependencies in node_modules folder in project.

cd nodejs-zip-unzip-files && npm install

Add folder and files to be zipped

We need a folder and some files inside folder to zip. So open public folder and add a new folder named Uploads, This folder contains files to be compressed. Add some images or text files in this folder.

Install express-easy-zip module

Open command line, go to project folder, and install express-easy-zip node module. This module is used to zip or compress files.

npm install express-easy-zip

Creating Zip and Unzip routes

Open project in your favorite IDE such as Sublime text, Eclipse or brackets.

First uploads directory inside public folder is assigned to dirPath variable. Then res object’s zip method is assigned a files array. Inside files array an object is passed. In object we passed a file contents dynamically with its name, mode, created date and type. This file named test-file is going to be compressed.

Next a folder uploads with full path is given. Contents of this folder are going to be compressed. Lastly name of zip file is given.

Running the application to zip or unzip file using nodejs

To run this application, go to project folder on Command Prompt. Type

node bin/www

Now open browser and type following URL is address bar.

http://localhost:3000

You can view our application running on port 3000. When user clicks on Zip and Download Files link button. /zip route is executed.

A zip file with a text file named test-file and uploads folder is created with name ‘Nodejs-zip-file.zip‘. User is prompted to save the generated zip file. Detail about option to be used in the zip can be read here

Unzip a file using NodeJS

To unzip a compressed file contents, first you need to install unzip NodeJS module.

What are Nodejs Streams?

Consider streams as objects. These objects can read data from a source and write data to a destination continuously. A stream can be readable to perform read operation, writable to perform write operation, duplex to perform both operations or a transform.

A new route unzip is added in index.js file. Inside route, path to an already compressed zip file is added. Zip file is inside compressed folder under public directory.

Next path to unzip folder is added, where compressed file contents will be uncompressed.

var destPath = __dirname + "/../public/unzip";

Lastly using fs module, a read stream is created using createReadStream. Inside readStream zip file path is given. readStream reads the contents of this file and passes to pipe stream.

Pipe stream takes input from one stream and pipes it to unzip module’s Extract method. Inside extract method destination path is given. File is unzipped in destination folder successfully and user is redirected to ‘/’ route.

Summary

In this tutorial you have learned how to zip or unzip files using NodeJS. Zip and unzip modules were installed and compressed files inside uploads folder. Then uncompressed a zip file present inside compressed directory. You can download source code from this link. Leave your feedback or comments below.

Please follow us on twitter to stay informed about upcoming tutorials.

]]>http://programmerblog.net/zip-or-unzip-files-using-nodejs-tutorial/feed/0How to create RESTful web services in codeigniterhttp://programmerblog.net/create-restful-web-services-in-codeigniter/
http://programmerblog.net/create-restful-web-services-in-codeigniter/#respondSat, 24 Jun 2017 21:29:26 +0000http://programmerblog.net/?p=753Last updated:24th June, 2017RESTful web services in codeigniter RESTful web services are a way of communication among computer systems. REST services are based on REST architecture. World wide web has resources like images, videos, web pages and other business information. Web service clients use URIs to request these resources. Response to the web service request …

RESTful web services in codeigniter

RESTful web services are a way of communication among computer systems. REST services are based on REST architecture. World wide web has resources like images, videos, web pages and other business information. Web service clients use URIs to request these resources. Response to the web service request can be in JSON, HTML, XML or some other format. In a previous tutorial you learned about SOAP web services in php using nusoap. This tutorial is about how to create a RESTful web services in codeigniter. A resource cane be created, modified or deleted using HTTP methods like GET, POST, PUT or DELETE.

To create restful web services in codeIgniter, following tasks would be performed.

1. Create a books database and table

2. Add sample data to table

3. Setup a codeigniter application

4. Create a RESTful library file, a model and an API controller to application.

5. Create API methods to fetch a book information via ISBN or fetch all books records.

6. Create add new book, update book and delete a book record methods to API

7. Test API with Google Chrome Postman extension

Create a books database and table

In order to create RESTful web services in codeigniter first you have to install PHP, MySQL. If you have not installed PHP and MySql, then visit WAMPor XAMPP website, download and install php mysql. After installation, open PhpMyAdmin. Click on SQL tab and execute queries given below.

Create a codeigniter application

As we have to create RESTful web services in codeigniter; so latest codeigniter version is required. Visit codeigniter website and download latest version of codeigniter and unzip it. Create a folder restful-services-in-codeigniter in htdocs or wwwroot folder of your php installation.

Copy the contents of CodeIgniter folder including application and system folder. Rename application folder to appx andsystem folder to sysx.

Open index.php file and change line no. 100 to

$system_path = 'sysx';

and line no 117 to

$application_folder = 'appx';

Open config.php file in config folder and go to line 26 and change base_url to

$config['base_url'] = 'http://localhost';

On Line 38 change index_page to $config[‘index_page’] = ”;

Open database.php file and change database settings. Update hostname, username, password and database name according to your MySQL installation.

Download REST controller and related files

Visit Github codeigniter rest server repository and download following files and copy to project directory as described below. Adding these files to project is necessary to create RESTful web services in codeigniter. Open libraries folder and create a file REST_controller.php and add code from this file. Create a file Format.php and add code from this link.

HTTP methods

We are going to use following HTTP methods.

GET

Get method is used to fetch data about a resource. In CodeIgniter $this->get() method is used to get parameters from URL or Query String.

POST

POST method is used to create a new resource. $this->post() method in CI is used to access values sent by client.

PUT

To update an existing resource PUT method is used. CodeIgniter’s $this->put() method is used to access values.

DELETE

To delete a resource this method is used. In CodeIgniter $this->delete() method is used.

Creating a model for book

In this tutorial on RESTful web services in codeigniter, we have to create a model for books. Open Models folder and add a file Book_model.php. Add following code into this file.

This book model class is extended from CI_model class. In constructor database class is loaded.

$this->load->database();

Fetch book by ISBN method for restful web services in codeigniter

getbookbyisbn method is defined. This method fetches a book record based on ISBN. $this->db->get() method returns a result object. num_rows contains rows in result. If there is a record then result array is returned.

Fetch all books method for restful web services in codeigniter

To fetch all books from a database getallbooks method is defined. This method selects and returns all books records.

Delete a book method for restful web services in codeigniter

Delete method is defined for deleting a book record. It accepts id. Id is passed to $this->db->where. $this->db->delete method is called with tbl_book. If query is executed successfully record is deleted and true is returned.

Add a book method for restful web services in codeigniter

To add a new record to database, Add method is created. Add method accepts $data array containing values for all columns in tbl_books table. $data array and table name tbl_books are passed to $this->db->insert method. On successful insertion true is returned.

Update a book method for restful web services in codeigniter

To update an existing book record, update method is defined. This method accepts id of record and a data array of values to be updated. In $this->db->where clause id is passed and then in $this->db->update data and table name are passed. Data is updated successfully and true is returned otherwise false is returned.

Adding API controller

Let us create an API is required so that clients can access API methods. Open controllers folder. Add a file API.php. Add the code below in this file.

Defining methods with get, post, put and delete

In the code above note that HTTP methods get, post, put and delete are used with each method name. But when these methods are called from a client get, post, put and delete are not used.

To fetch record from a database _get is added with function name but to create a new resource or to update _post or _put and _delete is used with delete method.

Controller method to get books by ISBN

To get a book information by ISBN the function bookByISBN is created. You can view _get added with function name.

$this->get is used to get variable values from URL or query string. If no ISBN is specified by client then a response code of 400 is sent back to client otherwise this ISBN is passed to book_model‘s method getbookbyisbn.

Result is returned to client using $this->response method with status code 200. Otherwise 404 status code is returned with message invalid ISBN.

Get all books information method

To fetch all books information books_get method is created. Model’s getallbooks method returns information about all books from database. In case of success result is returned with status code 200 , otherwise error is returned with status code 404.

Add a new book using API method

To create a new book, addBook_post method is created with HTTP POST method. Client passes book information using post method from web service client. Using $this->post values are assigned to variables. If any of the value is missing response code 400 or bad request is send back with message to client.

Data array is passed to model’s add method. If data is saved into database and a response code 200 is sent back to user with a success message, Other wise a 400 request code this sent back to user.

Update book method

In order to update a book information updatebook_put method is created. put is HTTP method to update a resource. All required values are assigned to variables using $this->put method.

If any of required parameters are not sent by client a response code 400 with a message is sent to client. Otherwise book_model‘s update method is called and data array is passed with book id. On successful update success message with status code 200 is sent to user otherwise a 404 response is sent back.

Delete a book method

To delete a book record using API method deleteBook_delete() method is created. In the method $id is assigned using $this->delete() method. If there is no $id then a 404 response is sent to client. Otherwise $book_model‘s delete method is called. On success status code 200 otherwise a status code 400 is returned.

Testing web service using Postman Chrome extension

Web services can be consumed by multiple clients. A client can be a PHP, ASP.Net application or a mobile app. In this tutorial creating restful web services in codeigniter we are going to use google chrome’s Postman extension.

Open Google Chrome browser. Click Window menu in top menu and click Extensions. Click on the link Get more Extensions in bottom. In Search bar on left side enter postman and click search. In available extensions search results click on Postman and click Add to Chrome. After installation click on Launch button. Let us test web service.

Postman Google Chrome extension

You can see in this extension user can select HTTP method, Enter request URL or can add params.

Selecting HTTP Methods

If you click on the drop down with GET parameter value, other HTTP methods that can also be selected.

Address bar URL and Parameters

In image below you can see address bar for adding web service URL with a button to add parameters. Clicking on Send button, web service request is sent to server.

Testing get books by ISBN method

Open postman and add following URL in address bar. Here port 8888 is used by MAMP on a MAC system. Do not use port if If your WAMP or MAMP installation do not have it. Select GET from methods drop down.

http://localhost:8888/restful-services-in-codeigniter/api/bookbyIsbn

Next an ISBN is added as a parameter. Click on Params button. In Key textbox enter isbn and in values textbox enter 978-0071492478.

Click on Send button and on success, result is sent back to browser.

Testing 400 Bad Request

If you do not specify a parameter while calling to a web service a bad request is returned.

Testing 404 not found request

If an invalid ISBN is entered then a 404 Not Found status code is returned with a message.

Testing Get All Books method

To get all books records, you need to call books method, notice we are not using _get with this method call. In postman add the URL below in address bar.

As there are no parameters; so click on Send button. Request is sent to server, in response all book records are returned as a JSON a object

You can see in picture above, result is returned from web service.

Testing add a new book using API method

In order to test add new book method, let us first view existing records in database. Currently there are 10 records in database.

Now in Postman select POST from HTTP methods drop down. Add following URL in address bar.

http://localhost:8888/restful-services-in-codeigniter/api/addbook

Adding a book using POST method, parameters are sent as part of body. Click on Body tab below address bar and select x-www-form-urlencoded radio button.

There are text boxes for keys and values. Add all parameters for the new book. Key is the name of column and value contains the data to be saved. Like name= Complete Reference ASP.NET MVC and so on. After adding data, Click Send button. If insertion is successful a success message is returned.

You can see below newly added record in database at id = 11

Testing update book method

To update record of an existing book updateBook method is called using PUT HTTP method. Select PUT from HTTP methods drop down and add this URL in address bar.

http://localhost:8888/restful-services-in-codeigniter/api/updatebook

. Click on body tag and select x-www-form-urlencoded radio button. See existing book record at id =1.

In Postman add new book record in key value boxes under body tag. Add id key with value 1. After adding book information click Send button. You can see success message and updated information.

You can view the updated record below.

Testing delete a book method

To delete a book from database using API deleteBook method is used. Open postman and add following URL in

http://localhost:8888/restful-services-in-codeigniter/api/deletebook

.From drop down select delete method.

Suppose you want to delete a book with id =11 from database. So in key value boxes add id as key and 11 as value. Click on Send button. Success message is returned from server after deletion of book.

Summary

To summarize, in this tutorial your learned to create restful web services in codeigniter. Then how to call and test web services using a client such as Postman Google Chrome extension. Hope this tutorial is helpful for you.

Please leave your feedback and comments. Follow us on twitter to stay updated about the upcoming articles and tutorials. You can download source code of the tutorial from this link.

]]>http://programmerblog.net/create-restful-web-services-in-codeigniter/feed/0How to generate RSS Feed using NodeJS and MySQLhttp://programmerblog.net/how-to-generate-rss-feed-using-nodejs/
http://programmerblog.net/how-to-generate-rss-feed-using-nodejs/#commentsFri, 26 May 2017 20:42:45 +0000http://programmerblog.net/?p=906Last updated:27th May, 2017Generate RSS Feed using NodeJS RSS (Rich Site Summary) is a way of delivering dynamically changing content. RSS is used to share information on internet mostly by blogs, news sites and publishers. In a previous tutorial we discussed how to generate xml using node js. In this tutorial you are going to …

Generate RSS Feed using NodeJS

RSS (Rich Site Summary) is a way of delivering dynamically changing content. RSS is used to share information on internet mostly by blogs, news sites and publishers. In a previous tutorial we discussed how to generate xml using node js. In this tutorial you are going to learn how to generate RSS feed using NodeJS and MySQL.

In this tutorial you will learn to.

1. Create a database and a table for news and insert sample news data.

2. Generate an express application to generate rss feed using NodeJS.

3. Use Node orm module to fetch data from database.

4. Use feed module to generate rss feed using nodejs .

5. Use fs module to save generated rss file.

To complete this tutorial you need to first install NodeJS and MySQL on your system.

Install NodeJS and MySQL

Visit NodeJS website to download latest version of NodeJS. After download run NodeJS installer. To install MySQL and PHPMyAdmin go to WAMP or XAMPP website. Download and install XAMPP.

Create News database and table

Run WAMP or XAMPP. Open PHPMyAdmin and Click SQL tab. Execute queries given below.

CREATE DATABASE IF NOT EXISTS `dbnews` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `dbnews`;
-- --------------------------------------------------------
--
-- Table structure for table `tbl_news`
--
CREATE TABLE `tbl_news` (
`id` int(11) NOT NULL,
`title` varchar(600) NOT NULL,
`description` text NOT NULL,
`publish_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_news`
--
INSERT INTO `tbl_news` (`id`, `title`, `description`, `publish_date`)
VALUES
(1, '''Guardians of the Galaxy Vol. 2'' Rockets to No.1 with $145 million', 'LOS ANGELES, (Variety.com) - And just like that, Star-Lord and his band of super buddies are back on top of the box office.', '2017-05-08'),
(2, 'Mars Science Lab launch delayed two years', 'NASA''s launch of the Mars Science Laboratory -- hampered by technical difficulties and cost overruns -- has been delayed until the fall of 2011, NASA officials said at a news conference Thursday in Washington.', '2008-05-09'),
(3, 'Nasa runs competition to help make old Fortran code faster', 'Two coders will share a $55,000 prize for what a Nasa official calls the "ultimate ''geek'' dream assignment.', '2017-05-04'),
(4, 'Retro tech: Flying car prototypes', 'How flying cars have gone from being a science fiction fantasy to almost becoming a reality, as seen through the BBC archive.', '2017-05-03'),
(5, 'Antarctic iceberg crack develops fork', 'The fissure that will lead to the breakaway of one of the largest bergs ever seen has a new branch.', '2017-05-02'),
(6, 'Secrets of tea plant revealed by science', 'Botanists unlock the genetic workings of the tea plant, in a move that could improve flavour.', '2017-05-01'),
(7, 'Machine learning', 'Many people are unsure about what machine learning is, but the chances are they are using it every day.', '2017-04-25'),
(8, 'In the Future, Virtual Assistants Will Also Have Ideas of Their Own', 'Assistants could proactively recommend ways in which humans could be living better lives, from getting more exercise to watching informational videos.', '2017-05-06');
ALTER TABLE `tbl_news`
ADD PRIMARY KEY (`id`);
ALTER TABLE `tbl_news`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

Include orm, feed and fs modules

First feed module is included to generate rss feed from database records. Secondly orm module is included to connect and fetch records from database. fs module is used to save generated RSS feed to a file.

Path to save RSS feed

Open public folder and create a folder named rss. In index.js define path to save generated rss file. RSS file is saved with the name rssfeed.xml.

var dirPath = __dirname + "/../public/rss/rssfeed.xml";

Connect to database using Node ORM and create a model

Applcation connects to database using orm’s express method inside router.use method. Username and password with database name are passed, in second parameter in orm.express, a model is defined inside define and a function that accepts database object, models and a parameter next.

Model for news database table is defined. Inside db.definetbl_news is passed. Next database table columns are mapped. Mapped columns are title as String, description as String and publish_date as Date.

Inside ‘/’ router req.models.news.find method is used to fetch data. An anonymous function is defined that receives err object and news result set. After result is returned, we loop through it to add news items to feed.

for(var i=0; i< news.length; i++){ .. }

Format publish date

Inside loop, publish_date is formatted using .toISOString method and substring 10 characters to get year, month and day.

Create a feed of news items

To create a feed of news items, feed.addItem method is used. A news item is passed as an object with parameters like title,link and description with author’s name, email and link to author’s profile, last parameter is date.

Save rss feed to a file

To save generated RSS feed to a file, fs module’s writeFile method is used and full path with file name and RSS document are passed. Finlay index view is rendered and a success message is displayed to user.

Running the app

In order to run the app, open command line and type.

set DEBUG=generate-rss-feed-using-nodejs:* & npm start

Now open browser and type URL given below in address bar. RSS feed is generated and saved in specified path.

http://localhost:3000

Summary

To summarize, in this tutorial you learned to generate rss feed using nodejs. Feed and orm modules are used to fetch data from database and generate RSS feed. You can download example source code by using this download link.

Run npm install on command line to install all required modules before running example code.

Please leave you feedback and comments. Follow us on twitter to stay informed about upcoming articles and tutorials.

]]>http://programmerblog.net/how-to-generate-rss-feed-using-nodejs/feed/4Generate XML with NodeJS and MySQL using XML builderhttp://programmerblog.net/generate-xml-with-nodejs-and-mysql/
http://programmerblog.net/generate-xml-with-nodejs-and-mysql/#commentsSun, 14 May 2017 12:00:57 +0000http://programmerblog.net/?p=901Last updated:14th May, 2017How to generate XML with NodeJS XML is a popular information exchange and storage format on internet. XML is used in web services, RSS Feeds and many other technologies. In a previous tutorial we discussed How to parse XML using NodeJS, this article explains how to generate XML with NodeJS and MySQL. To …

How to generate XML with NodeJS

XML is a popular information exchange and storage format on internet. XML is used in web services, RSS Feeds and many other technologies. In a previous tutorial we discussed How to parse XML using NodeJS, this article explains how to generate XML with NodeJS and MySQL.

To access data from MySQL Node ORM and to generate XML xml-builder modules are used. Suppose there is a Book Store application where we need to share books information with other users, so we generate XML with NodeJS containing books data. So in this tutorial we are going to:

1. Create a books database and table using MySQL

2. Insert sample data into the table

3. Create a NodeJS, express application

4. Install necessary plugins such as Node ORM and XML Builder.

5. Fetch data from database, generate XML using nodejs and save to a file.

Create a database and table for books

First you are going to create a MySQL database and a table for storing books information. To use MySQL install WAMP or XAMPP. After installation, Open PHPMyAdmin. Click MySQL tab, copy and paste following SQL queries and execute.

Queries above creates a database dbbookstore and a table tbl_books. Then sample data is inserted into the table.

Create a NodeJS and Express app to generate xml using nodejs

If you have not installed NodeJS yet, then visit nodejs.org website and download NodeJS. Install it according to you system. Using NPM Install express generator. On command line, type following command.

express --view=pug generate-xml-using-nodejs

This command generates a NodeJS and express application to generate xml using nodejs.

After generating application type command below.

cd generate-xml-using-nodejs && npm install

This command changes directory to project folder, installs all required modules. To run this app, type

To connect MYSQL database and fetch table data you have to install an ORM or Object relational Mapper. Node ORM module is used to perform database related queries. You can create models, validations or run queries easily using an ORM. Type command.

npm install orm

Install xmlbuilder module to generate XML with nodejs

After data is fetched from database, XML file containing all books information is generated. For this purpose xmlbuilder module need to be installed.

npm install xmlbuilder

This installs XML builder module to convert books data to XML file.

Generate XML with NodeJS

Open index.js file in routes directory, remove all code and add the code below

After connection to database a model is defined for table. An anonymous function accepts 3 parameters such as database object db, models and next. Inside define a new model for book table is created.

Using db.define method, table name tbl_book is passed and second parameters are table column names with their data types such as name : String, price: Number etc. After model is defined inside ‘/’ route, data is fetched from database using find method.

Create XML builder object with root element

Inside ‘/’ route xmlbuilder object is created and a root element is passed. Every XML document have a root element, in this case it is bookstore.

var xml = builder.create('bookstore');

Next all books information is fetched from database using request.models.find method. Inside find method two arguments are passed, first parameter is criteria and second is the anonymous function.

Fetch data to generate XML using nodejs

Inside req.models.book.find method, first argument is the criteria. Criteria in this case is empty as we want to fetch all records. Second parameter is a function that accepts an error and books variable that contains information of all books. Find method returns all the data from database table. Inside function we use create XML file.

Add elements and attributes to XML document

In order to add each book information to XML document a loop is performed. XML object’s method .ele accepts book as main element to embed other book information. Then other elements are chained using .ele method with name element and inside name element, an attribute named lang is added as an object with language value.

Other elements such as price, category, author, isbn and publish_date are added using .ele method. up method is used to close the tags. Lastly .end method is used to close book element.

Convert XML document to a string

xml object is converted to a string using .toString method. A parameter {pretty : true} is also passed.

var xmldoc = xml.toString({ pretty: true });

Save generated XML to a file

To save generated XML to a file, we use fs module’s writeFile method and pass destination file path, XML and a callback function. Call back function provides err, if err occurs it throws an error. This generates xml using nodejs.

index.js file is rendered and a message is displayed to user that XML file is generate successfully.

Summary

To finalize, in this tutorial you have learned about how to generate XML with NodeJS. Node ORM is used to fetch books data and xmlbuilder to generate XML from this data. Source code used in tutorial can be downloadedby clicking on this link.

Please leave your feedback and comments below. Follow us on twitter to get informed about upcoming tutorials.

]]>http://programmerblog.net/generate-xml-with-nodejs-and-mysql/feed/2How to parse XML using NodeJS, ExpressJS and xml2jshttp://programmerblog.net/parse-xml-using-nodejs/
http://programmerblog.net/parse-xml-using-nodejs/#commentsSat, 06 May 2017 16:14:38 +0000http://programmerblog.net/?p=868Last updated:6th May, 2017How to parse XML using NodeJS XML or eXtensible Markup Language is widely used to store or interchange data on internet. XML is derived from SGML and is human and machine readable. XML document can have custom defined tags. In a previous article we discussed how to generate xml using php , …

How to parse XML using NodeJS

XML or eXtensible Markup Language is widely used to store or interchange data on internet. XML is derived from SGML and is human and machine readable. XML document can have custom defined tags. In a previous article we discussed how to generate xml using php , this article explore how to parse XML using NodeJS.

Suppose you are working on an online book store application, and this application shares all available books information. You can generate a XML document containing information such as book name, category, price and author etc. This information can be parsed and displayed to users by other web sites.

In this tutorial we are going to:

1. Create a NodeJS, ExpressJS application

2. Parse a book information XML document using NodeJS

3. Display books information to user

Create a NodeJS, Express application

Open command prompt and type following command to generate a NodeJS, Express application.

express --view=pug nodejs-parse-xml

This command will generate an express application named nodejs-parse-xml. Type command cd nodejs-parse-xml. Type npm install to install the dependencies and modules. You can see the directory structure. pug is used as template engine.

Books information XML document

The XML file below is used to store information about the books. Create a directory xmlfiles in public directory. Create an XML file booksxml.xml with following information.

In the view file a table is created with headers Title, Category, Author, Year, Price and Language. Next we loop through a books information, displaying category, author and price. Title element that contains an attribute for language and value of booktitle are parsed differently.

<title lang="en">The C++ Programming Language</title>

To display title“_” is used to display column value.

#{book['title'][0]['_']}

To display attribute lang. $is used with lang parameter to displays value of language attribute.

#{book['title'][0]['$']['lang']}

You can see the parsed XML result in the image below.

Summary

In this tutorial you learned how to parse XML using NodeJS and display this information to user. You can download the source code for this tutorial.

Please leave you feedback and comments. Follow us on twitter or subscribe to our newsletter to stay informed about upcoming tutorials and articles.

]]>http://programmerblog.net/parse-xml-using-nodejs/feed/2How to create web services in php using NuSOAP libraryhttp://programmerblog.net/web-services-in-php-using-nusoap/
http://programmerblog.net/web-services-in-php-using-nusoap/#commentsSun, 23 Apr 2017 19:52:49 +0000http://programmerblog.net/?p=406Last updated:2nd August, 2017How to create web services in php Web services are software available on internet. They can communicate and provide information to client programs based on XML messaging. In this tutorial we are going to learn about how to create web services in php using NuSOAP. We will also look in to the …

How to create web services in php

Web services are software available on internet. They can communicate and provide information to client programs based on XML messaging. In this tutorial we are going to learn about how to create web services in php using NuSOAP.

We will also look in to the basics of web services, SOAP and learn to develop web services in php.

1. Create a MySQL database and a table for books.

2. Insert sample data into the database table.

3. HTML form to get ISBN number from user.

4. POST form data to a php page and send to web service.

5. Create a web service that connects to MySQL database.

6. Fetch book information based on ISBN number and respond to client.

7. Client receives data from web service and display to user.

REST Web Services

Suppose you are working on a shopping cart application and need to calculate the shipping charges for the user, so instead you develop a new module to calculate shipping, can use a web service from FedEx and get required information. To fetch information about a book based on ISBN, Amazon book web service can be used.

Web services can be implemented using REST or SOAP techniques. REST means you are using existing services or technologies to get content from internet. Web services can be implemented in different languages and platforms. To use a REST web service you only need the URL or contract of the web service, parameters and what information is sent back.

eBay web service

eBay has many services that provide information about the products etc. There is eBay GetSingleItem Web Service, this web service can return product details, shipping cost, summary etc. To get this basic information eBay has provided a basic URL and you have to providean ItemID.

SOAP web services

SOAP or Simple Object Access Protocol is a communication protocol to exchange messages among computers. To work with SOAP you have to understand different soap elements.

SOAP Envelope

For sending and receiving messages, SOAP has a standard format. SOAP standard is defined by W3C. Every SOAP message is an XML document and has a root element called SOAP Envelope.

SOAP Envelope has an optional tag called header and a mandatory tag called body. Inside body there are all the parameters such as what information you will send to the methods and what information is returned. SOAP is a contract between client and the server.

WSDL or Web Service Description Language

WSDL is a standard by W3C. It serves as a contract between server and client. WSDL contains location of web service, operations and parameters. Operation tags tells that what methods are available. Message tag tells format of messages.

Web services can be implemented by whatever language you want. Every language has set of tools available to implement it. PHP has php SOAP extension. The other popular tool available is called nuSOAP. Let us explore how to create web services in php using NuSOAP library.

Create a MySQL database and table

First we are going to create a database and a table for the web service. Open phpMyAdmin on your computer and click SQL tab. Execute following queries.

Create project folder php-webservices

Open www or root directory of your WAMP or XAMPP installation. Create a folder php-webservices. Download NuSOAP from Sourceforge website. Extract and copy lib folder, paste it in folder you have created above.

Create database connection file using PDO

Create a file named dbconn.php and add php PDOcode to connect to database.

A function fetchBookData($isbn){ … } is created. This function will acts as web service. It accepts a parameter as $isbn.

To use database connection object from dbconn.php, $dbconn is declared as a global object. A query is defined to fetch a book record with $isbn as named parameter.

A prepared statement is created using PDO Prepare method. bindParam method binds $isbn to ISBN parameter. execute method runs the query and database record is returned to $data variable. To fetch data into an array fetch() method is used. Data is json encoded and returned to client web service.

Configure a WSDL for web service

To configure a WSDL, configureWSDL method is used.

$server->configureWSDL('booksServer', 'urn:book');

This method takes two parameters. First parameter is name of WSDL document bookServer and second parameter is the namespace. It is Universal Resource Identifier, it differentiates WSDL from other WSDL documents.

The code snippet above registers fetchBookData function as a web service. The other information to provide are the input and output parameters. This web service takes a string parameter as input and returns a string as an output.

xsd means XML schema is used. With XML schema we have pre-defined data types such as integer, string, float etc. Namespace and name of the method is provided.

Display WSDL document

Open you web browser and type following URL in the browser.

http://localhost/php-webservices/webservice-server.php

You can see a nicely formatted page like above. If you click on WSDL link, displays a WSDL.

In the bottom of this document, inside service tag, name of web service in mentioned as a parameter. SOAP address tag’s location parameter contains the location of the web service. An operation tag contains name of fetchBookData web service. fetchBookDataRequest message tag specifies that web service requires ISBN prameter as a string. fetchBookDataResponse tag specifies that web service returns a string as output to client. Now this web service is ready and waiting for a client web service to contact it.

Client web service can be implemented in any language. A client needs to send a SOAP message in a particular format defined by WSDL.

Create HTML form to get ISBN form user

After setup of server let us work on client side. HTML form is created to get ISBN from user and send it to server. Create a file webservice_client.php. Add following code to create a form.

In the code above we first include nusoap from lib directory. Then create a $WSDL variable and assigned it the path of WSDL. Next we check if user has entered an ISBN and submitted the form. A client object of nu_soap is created using

$client = new nusoap_client($wsdl, true);

Two parameters are passed to this functions , first is path of WSDL and second argument is true that tells that the first parameter is a WSDL. We use client object’s call method to call a web service.

A table is added with Title, Author, Price, ISBN and Category table cells. If result is returned from web service it is displayed to user in a loop.

Web services in php – web service response

Summary

To summarize this tutorial you have learned about basics of web services in php and created a web service using NuSOAP library. Data is fetched from MySQL database by web service and displayed to user. You can downloadcomplete source codewith MySQL database dump.

Please leave you comments of feed back in the comments. Stay tuned for more cool tutorials. Please follow us on twitter to get latest information and knowledge on web development industry.

NodeJS Passport login with MySQL

User authentication is an important feature in today’s dynamic applications. This tutorial explores NodeJS passport login with MySQL. In a previous Nodejs mongodb tutorialyou learned about performing Insert, Update, Delete and View records, but these tasks need to be performed by an authenticated user. This tutorial explores this important feature.

To do nodejs passport login with mysql, following tasks are performed.

1. Create a database db_users.

2. Create a database table for tbl_users and insert sample data into the table.

Change host name, username, password and database name according to your system settings.

Install passport and other modules

In order to perform nodejs passport login with mysql, you have to install Passport and other modules. Open command prompt, navigate to nodejs mysql login project directory and run commands given below.

Passport module initialization

PassportJS local strategy for Signin

Passport module LocalStrategy is used to authenticate user locally. Other then local strategy user can be authenticated using Twitter or Facebook etc. In LocalStrategy a verify callback is required and credentials are passed to it. done method is called. If username and password are not entered an error message is displayed to client.

PassportJS login process

Passport LocalStrategy is called local, and username and password fields are specified. Request object req is passed to callback function. A SALT is defined and is concatenated with password. A query is passed to connection.query() method of mysql driver to fetch user information based on username entered by user.

If provided username is not correct then an error message is displayed to user, if username is correct then password concatenated with SALT and is hashed with sha1 algorithm using crypto module. If password is correct user information is returned.

To authenticate requests using passport we have to use passport.authenticate and specify local strategy.

If user is signed in successfully, is redirected to profile page, if signin is failed, user is redirected back to signin page and appropriate message is displayed.

To view running signin page, open browser and type following URL

http://localhost:3000/signin

Protect routes with isAutehticated

Request object’s isAuthenticated method is used to validate whether user is logged in or not. So if there are routes like profile that needs to be protected from public access and should only be visible to authorized user, isAuthenticated is added in route.

router.get('/', isAuthenticated, function(req, res, next) { ... }

The code below checks if user is authenticated then redirected to next page otherwise redirected back to login page.

Summary

In this tutorial you have learned about nodejs passport login with MySQL. We created a database and table. Created a form with bootstrap. Installed passport and other related modules, added a local strategy to perform signin and authenticated a route.

Stay tuned to for more great tutorials. To download the tutorial code visit following link. Follow us on twitter to get informed about upcoming tutorials. Leave your comments and feedback below. thanks for reading.

php mongodb tutorial

Mongodb is very popular open source, document based NoSQL database. In a previous NodeJS mongodb tutorialweexplored how to perform CRUD operations on mongdb database using nodejs. In this php mongodb tutorial you will learn how to fetch, insert, edit, delete records in a mongodb collection using php.

In this article following tasks are done:

1. Create a database in mongoDB

2. Create a mongodb collection

3. Insert data into mongodb collection

4. Display records in a page from mongodb using php

5. Insert, update, delete records from mongodb database using php

Create database in mongodb

To create a database in mongodb, “use database_name” command is used, if database does not already exist, a new database is created.

> use onlinestore
switched to db onlinestore

View all databases

To view all databases in mongodb, type > show dbs.

> show dbs
local 0.000GB
onlinestore 0.000GB

View current database name

To view current database.

> db
onlinestore

Create a mongodb collection

db.createCollection(collectionName) is used to create a collection.

> db.createCollection("products")
{ "ok" : 1 }

Insert records to mongodb collection

In order to insert records to mongodb collection insert method is used. To insert bulk records, all records are added in an array.

mongodb find method to fetch records

find() method fetches records from mongodb collection.

db.products.find()

php mongodb extension to access database

Install php mongodb driver

To work with mongodb in php you have to install php mongodb extension. Visit php mongodb packagessite and download mongodb driver package compatible with your php version and OS. Unzip and paste php_mongo.dll file inside your WAMP or XAMPP php installation extension folder. Suppose you have installed XAMPP, Then go to php folder and open ext folder like C:\xampp\php\ext.

Enable mongodb extension in php.ini

Open php.ini file and enable php_mongodb extension.

extension = php_mongodb.dll

After installation of mongodb driver, restart Apache web server. In root folder if you create a php file and call phpinfo() function you can see mongodb extension is loaded.

php mongodb database connection

After mongodb is installed now inside www or public_html folder of your WAMP, XAMPP or LAMP create a directory phpmongo. Create a file config.php. Add the code below to the config file

To connect to a mongodb database mongodb driver manager is used. All database connections are maintained by mongodb driver manager. Database connection is not created on instantiation of a mongodb driver manager object.

Driver manager takes parameter server address localhost with a port 27017. A messages array is created to save success or error messages to be used later.

PHP mongodb select and display records

Create a file index.php. This page displays records from a mongodbcollection.

config.php is included into index.php to use mongoDB drivermanager object. When ever a new record is inserted, updated or deleted, user is redirected back to index page with a flag as query string parameter. Based on flag parameter a message from messages array in config is displayed to user.

Next $filter variable is created. Filter can contain any condition to be met to select a records. For example it can be set to select the documents where price is greater than $50. If you are familiar with relational databases then you can consider it as a where clause.

$options array contain additional options such as sorting. mongodb driver’s Query method is used to construct a query and accepts filter and options parameters.
executeQuery method is used to execute a query. Database collection name and a query object is passed to this function and on success a mongodb driver returns a cursor or an exception is thrown otherwise.

Display all records in a loop

To display all the records to user a table is created with table cell headers #,product name, price, category and action. Using foreach loop all records are displayed from $cursor array.

With product name, price and category, Edit and Delete links are also displayed. Edit link is assigned a class .editclass. This class is used to fire a click event and sends an AJAX request to server when any edit link is clicked. A data-id attribute is added inside edit link and _id value is assigned o it.

Delete link redirects a user to record_delete.php page. A confirmation message is added that confirms record deletion from user.

PHP mongoDB Insert record

To add new documents into a mongodb collection first a form is created inside index.php. Then product_name, category and price fields are defined. A hidden field id is also added. In case of update of a record it contains id of existing record. Form data is posted to record_add.php page.

Create a php page record_add.php. This page includes config.php page to access to mongodbdrivermanager object to make a connection to mongodb and insert a document to collection. Inside if condition we get product_name, price and category from $_POST super global array. If any of values not entered error code 5 is sent back to user.

Write operations are added to MongoDB\Driver\BulkWrite and are sent to the server. After adding insert, update or delete operations to bulkwrite operations can be executed.

MongoDB\Driver\WriteConcern is used for describing level of acknowledgement requested from MongoDB. Write operations are executed by executeBulkWrite. It accepts collection name, bulkwrite object and writeconcern.

PHP mongodb update record

Fetch existing record form database

To update a record user clicks on Edit link an AJAXGET request is sent to server and server responds with data of clicked document. To send an AJAX request in JADE template engine you can use code below.

First jQuery library is included from jQuery CDN and then inside jQuery ready function an event for the edit links class .editlink is created. Whenever an edit link is clicked this event is executed. $(this).data(‘id’) .val() gets the _id value from data-id attribute of currently clicked link. Using jQuery’s $.ajax method a request is sent to fetchdata.php.

After id parameter is received a filter is created and is converted to mongodb object id. A query is created by passing $filter and $options array. Collection name and $query is passed to executeQuery method and it returns mongodb cursor that contains the records.

Next from cursor data is assigned to array. After encoding data to JSON it is sent back to client side.

Now create a page record_edit.php and add code below into it. User modifies data in the form and clicks ‘Update Records‘ button, server receives request and data is assigned to variables from $_POST array.

Update records into database collection

If user enters all the data correctly then inside else clause a mongodb driver bulkwrite object is created and update command is added to it. bulkwrite object’s update method accepts id and edited data. Here multi =>false means that we are only updating one record.

To update all documents that matches a certain criteria multi parameter is set to true. Upsert parameter if set to true creates a new document if criteria is not met. In this case it is set to false, so it does not create a new document.

record_delete.php page gets id from URL query string and creates a bulkWrite object. Next a delete operation is added to bulkwrite object where id of record is passed and limit is set to 1.

After creating writeconcern object, executeBulkWrite method runs query and takes collectionname, bulkwrite object and writeconcern parameters. After record is deleted user is redirected to index.php page.

Summary

To summarize, this tutorial explores how to perform CRUD operations on a mongodb collection using PHP. Find the php code and mongodb queries in this download link. Follow us on Twitterto keep updated on latest tutorials and articles.