Mongodb CRUD operations using PHP

mongodb-crud-operations-using-php What is MongoDb?

MongoDB is an open source document oriented nosql database. It is powerful, extremely fast, flexible and highly scalable database. It stores data in the form of JSON like documents BSON(Binary JSON).

Basics of Mongodb

Collection :  In mongo database, data is stored in Collections. These are equivalent to tables in relational database.

Document : Document represent a record in MongoDB collection. We can store integer, string, array, objects and many more type of data as a document in collection.

Schemaless: Mongo has no schema for storing document, we can store any type of data in any cell of a row.

To install mongodb follow this article¬† “How to install mongodb” and install andy GUI tool like MongoVue or Robomongo for better understanding.

Mongodb CRUD operations using PHP

Create records

Single Insert
Consider a scenario where we want to insert user details in “user_details” collection in “users” database.

That’s it, we have inserted a new record and i think you didn’t noticed one thing and that is “we don’t have to create any database or table(collection) or schema in order to create record in mongo“.

mongo-insert-using-php

Now, if you are dealing with a single database then specify database as follows.

Last insert id can be obtained using following syntax, remember that mongo create a default unique and indexed id as _id and it’s an object not string. Check the image at the end.

Bulk Insert
Consider a scenario where we want to insert multiple records at once, then we write it as follows.

Above batch insert shows that you can insert any data type in any field.
In first case, we entered age as string instead of integer (as inserted before).
In second case, we entered a new field has_job and also remove age.
In third case, we entered a multi dimensional array and added a new field salary.

Above example shows that mongo is schemaless.

Applying Indexes
Index is applied on a collection using following query

 

Reading records
Consider a scenario where we want to read above records on the basis of various conditions, we will discuss each aspect one by one.

find function is used to fetch data, it returns a cursor to the data. “hasNext()” ensures that whether any data found or not. After that we have to iterate over cursor to get results, for this “getNext()” function is used.

To count number of results which is obtained from find query writes as follows

Find results with some specific conditions

Updating records

Let’s update some of the user details which we have entered above.

Here ‘multiple’ is used to updated all results with matching criteria, by default mongo will update only one result if we doesn’t pass third parameter in above query.

In the below image you can see data after updating records, in first case skills is an array and in second case it’s an object.

mongo-array-object

Below image shows when mongo is successfully connected then it shows connected as 1, second section shows last insert id and third section shows if update is successful then nModified and n is equal to number of rows affected.

mongo-connection-update

Deleting records

Deleting records is the easiest of all, it is done using following query

Always remember, delete by default works on all records and update works on single record.

That’s all in “Mongodb crud operations using php”.Do comment and subscribe for further updates.

Tips & Tricks for writing better PHP code

 tips-and-tricks-to-write-better-php.png

PHP is one of the widely used Server Side Scripting Language. It’s easy to learn PHP but it’s tricky to use it correctly. Let’s see some of the tips & tricks for writing better PHP code.

Variable Validation
Consider a scenario where we have to find array count or string length of a variable and we have to handle all kinds of errors and warnings.This sounds very simple but most of the newbies can’t complete it (with my experience) because they don’t know how to write quality code.
Let’s calculate length of a string

Let’s check for array count & loop through the each values

Return type of inbuilt function
PHP comes with so much of inbuilt funtions and of course it’s important to use them but always remember their “return type”. Let’s understand this with an interview of fresher which took some days ago.
Me: Can u tell me return type of date(“Y-m-d”) ?
Fresher: String
Me: Can u tell me return type of date(“YW”) ?
Fresher: Integer
And that’s the problem, for newbies return type means what they see as output, in this case if fresher saw 2016-01-02 then return type of date was string and if it was 201601 the it is integer, which is wrong.Return type of a function never varies with the output.

Free memory
Memory is a very important aspect of any application. PHP is not so good with it’s memory management by itself but we can take care of it with some simple tips as follows:

  • Unset the values when after it’s use.
  • while running an infinite loop (like in background services) always use gc_collect_cycles, this will collect any garbage cycles, thus reducing memory

Limit memory
It’s always good practice to limit memory of a php script.Say we have to set memory limit to 100Mb then we should write is as ini_set(‘memory_limit’, ‘100M’);

Follow MVC approach
Models deals with database(s), Controller contains logic and Views contains front-end design.It is the best approach to maintain your code and separate logic with design. MVC provides a single file to handle your incoming request, which makes it very easily to handle, debug and maintain requests

Use arrays
I prefer arrays over a simple variable just because it’s easy to maintain and perform operations on array than a single variable. But don’t overuse it, just use it wisely.

I hope these tips and tricks will help you to write more robust code.

Javascript: A Practical Introduction

practical-introduction-to-javascript

Javascript is one of the most trending and highly paid language in the tech industry right now.In my early days of my career, I struggled with javascript and soon realized that knowledge of implementing a slider or a plugin is not enough and I have to improve my basics to play with javascript. This article nucleus is “Practical Introduction to Javascript“.

Let’s begin with the very basic.

Window vs Document
Window: In very simple words “every tab is a window”. For example, window.close works when we close the tab.
Document: Whatever user see inside the tab is a document. For example, document.ready works when the page is fully loaded.

Alert vs Console.log
One of the worst and irritating way of checking output and debugging is “alert”. Javascript has got “console.log” function which is used to output data in the console of the browser.It has following benefits:

  • doesn’t freeze web page, it is non-blocking
  • shows very large output easily
  • easy to understand and explore insight of javascript objects

Validation
Generally, first thought comes in a fresher mind after hearing validation is form validation but here I explain you about “Variable Validation“. A variable can store form value, a random string, an array, an object or any value. Consider a scenario where we have to validate a variable and confirm that it contains some string value then the process I prefer is follows:

  • check whether the variable value is undefined or not
  • check whether the variable value is null or not
  • check for string length

Below function will solve the above problem with ease.

Array vs Object

When i take interviews, 95% of freshers don’t know the difference between javascript arrays and objects and believe me these two are the most used data type in javascript while developing fronted of any application.
Arrays can be “single dimensional only” in javascript. Eg.

Looping

Adding values to array and object

Above I explained some of the practical tips of javascript which I thought every newbie must learn to grow and hope these will be helpful for every developer thinking of learning javascript. Got any question, ask me now.

Best PHP RESTful Micro Frameworks

php-micro-frameworks

What are Micro Frameworks?

Before discussing which are the “Best PHP RESTful Micro Frameworks” let begin with the concept of micro-framework. Micro Frameworks is a term used to represent a small set of code and modules that are designed to do only basic tasks and functionality and at the same time they are highly extensible.These frameworks comes with less components than full stack framework but they have several libraries and patterns which are required to make a project of good quality and scalable.
Don’t think that “micro” represent for small projects, it only means “Framework bundled with less components”.

Best PHP RESTful Micro Frameworks

1. Silex

  • One of the fastest micro-framework
  • Built on top of Symphony components
  • Great documentation and community support
  • Good for large projects
  • Follows Symfony2 HTTP conditions
  • Automated functional tests

2. Slim

  • Super fast and extremely light-weight
  • Good documentation
  • Great community
  • Lots of tutorials on YouTube and on other websites
  • Lazy loading with 3rd party implementation
  • Bundled with middleware, caching, encryption of cookies

3. Lumen

  • Zero configuration
  • Excellent documentation
  • Ultra-fast micro framework
  • Good 3rd party support
  • Easily upgradable to laravel
  • Bundled with encryption, middleware, unit testing, caching,queuing and sql-nosql support

4. Phalcon

  • Blazing fast
  • Provides very high performance
  • Written in C-language
  • Compiled for better performance
  • Can handle more requests per second

5.Bullet PHP

  • Little learning
  • Unlimited flexibility
  • Flexible routing
  • Nested closure routing system

That’s all for today folks, try one of the above frameworks and do share your experience with me.

What’s new in PHP 7

Finally the most awaited version of php ie. PHP 7 is officially released.It’s been a long journey to make it bug free and efficient, 8 release cnadidates and finally it’s available to deploy.php-7

PHP 7 bundled with some massive improvements in speed and memory consumption, to be precise twice fast from php 5.6. I would like to congratulate the contribution team for their great effort.

PHP 7.0.0 comes with a new version of the Zend Engine, numerous improvements and new features such as

  • Improved performance: PHP 7 is up to twice as fast as PHP 5.6
  • Significantly reduced memory usage
  • Abstract Syntax Tree
  • Consistent 64-bit support
  • Improved Exception hierarchy
  • Many fatal errors converted to Exceptions
  • Secure random number generator
  • Removed old and unsupported SAPIs and extensions
  • The null coalescing operator (??)
  • Return and Scalar Type Declarations
  • Anonymous Classes
  • Zero cost asserts

PHP revolution begins now with the fastest version of php, get ready to explore the new things with great speed.
Check the complete list of features at php.net