Update Method: MongoDB

Lets learn how to update MongoDB document using update() method.

test database, names collection

1
2
3
4
5
6
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 27
}

Observe the document, with fields name and age. We’ll be illustrating update() method by working on this document.

update-method-mongodb

1
2
3
4
5
> db.names.update({"name": "Satish"}, {"age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "age" : 28 }

update() method takes at least 2 arguments. First argument being the condition(WHERE clause in sql) and the second argument being the fields to be updated. Observe that, whatever the fields we specify in the second argument are only retained(along with _id), all other fields will be erased.

1
2
3
4
5
6
7
8
9
> db.names.update({"age": 28}, {"name": "Satish", "age": 28});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28
}

Now we’ve updated with name as well as age field and it reflects in the document in the collection.

Update Method: MongoDB


[youtube https://www.youtube.com/watch?v=6LfvsoqRoP8]

YouTube Link: https://www.youtube.com/watch?v=6LfvsoqRoP8 [Watch the Video In Full Screen.]



1
2
3
4
5
6
7
8
9
10
> db.names.update({"age": 28}, {"name": "Satish", "age": 28, "salary": 200000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"),
        "name" : "Satish",
        "age" : 28,
        "salary" : 200000
}

If we want to update/add a new field to the document, we must also specify all other fields we want to retain in the document.

1
2
3
4
5
> db.names.update({"age": 28}, {"salary": 300000});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53c3c4b1a0eddb0a706e4f56"), "salary" : 300000 }

If we forget to specify other fields, then they will be erased(except _id field).

Access Specifiers: PHP OOP

Controlling Access with public, private and protected access modifiers.
These access specifiers can be used on both variables/attributes and methods.

In this video tutorial, we’ll demonstrate it using attributes.

Access Specifiers:
1. public
2. private
3. protected

Class With Attributes

1
2
3
4
5
6
7
8
9
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
?>

var $a is similar to writing public $a

We shall extend class container to another class called contains.
Extending class is an inheritance property, and we shall discuss inheritance in another article. For now, know that, with extends keyword, all the properties and methods with public / protected access are inherited.

Extends

1
2
3
4
5
6
7
8
9
10
11
12
13
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
?>

Here, contents of class container is extended by class contains.

Object of class container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj1 = new container();
         echo $obj1->a;
         echo $obj1->b;
?>

This outputs: 10 and 20 respectively.

Object of class contains

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj2 = new contains();
         echo $obj2->a;
         echo $obj2->b;
?>

This outputs: 10 and 20 respectively.
i.e., public attributes are inherited

Accessing private / protected attributes outside class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 }
 
 $obj1 = new container();
         echo $obj1->c;
         echo $obj1->d;
?>

It through’s error, since you cannot access, private and protected variables/attributes outside the class.

Now lets check if private and protected variables are actually inherited:

Inheriting private attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 function __construct()
{
echo $this->c;
}
 }
 
 $obj1 = new contains();
?>

This through’s error, because $c is not inherited to class contains and thus not present inside class contains. Which means, private variables and methods cannot be inherited.

Inheriting protected attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
 class container
 {
 var $a       = 10;
public $b    = 20;
private $c   = 30;
protected $d = 40;
 }
 
 class contains extends container
 {
 function __construct()
{
echo $this->d;
}
 }
 
 $obj1 = new contains();
?>

Output’s 40.
This means, protected variables and methods are inherited.

Access Specifiers: PHP OOP


[youtube https://www.youtube.com/watch?v=2Ow_cgBEGmk]

YouTube Link: https://www.youtube.com/watch?v=2Ow_cgBEGmk [Watch the Video In Full Screen.]



Conclusion
public attributes and methods are inherited and can be accessed outside the class.
private attributes and methods cannot be inherited and cannot be accessed outside the class.
protected attributes and methods can be inherited but cannot be accessed outside the class.

Object Oriented Programming Basic: PHP

Video tutorial illustrates basics of OOP in PHP.

Things covered:
Defining class.
Creating Objects.
Public and Private access of Properties/Data.
Separating Class file and the application file.

What is a Class ?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Class Add
add.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
class Add
{
private $a;
private $b;
 
function setValues($v1, $v2)
{
   $this->a = $v1;
   $this->b = $v2;
}
 
function add()
{
return( $this->a + $this->b );
}
}
?>

class is a keyword. Add is the name of the class we’ve assigned.
$a and $b are two variables of class Add. These have private access specifier, meaning, they’re not accessible directly from outside the class.
Public access specifier indicates that they can be accessed even outside the scope of a class. Private variables are treated as safe, so we prefer that.

Since private variables are accessed inside the class, we declared two methods inside the class Add. i.e., setValues() and add()
setValues() has two parameters which are then assigned to the local variables $a and $b using the $this pointer.

$this pointer references to the object which is currently pointing to it.

add() method adds the user passed values and returns the result.

Application File
index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
?php
 include_once('add.php');
 
$add = new Add();
 
$add->setValues(50, 100);
echo $add->add();
 
$add->setValues(150, 100);
echo '<br />'.$add->add();
 
$add2 = new Add();
 
$add2->setValues(500, 1000);
echo '<br />'.$add2->add();
 
?>

Here we include the add.php file and create an object of (class)type Add.
Using this object we pass values to setValues(), and then call add() method, which returns the added value of the passed numbers. which is then output to the browser.

We could create as many objects as we wish and then pass and output as many results as required, without altering the class file what so ever, once finalized.

So this is the power of Object Oriented Programming.
This way we could manage complex applications easily or in an organized/standard way.
Increase code re-usability.
Also reduce maintenance cost etc..

Object Oriented Programming Basic: PHP


[youtube https://www.youtube.com/watch?v=0smq5Lf6Q2k]

YouTube Link: https://www.youtube.com/watch?v=0smq5Lf6Q2k [Watch the Video In Full Screen.]



Why OOP in PHP ?
Most web projects still use procedural i.e., function based software development approach. And honestly, it has no issue, because most web projects are so small scale and straight forward that they don’t require OOP in most cases.

But for complex application development, you need OOP for effectiveness.
Like, if you want to build a home, you need a lot of planning, preparation and some standard approach to build it.

Reading XML File Using jQuery AJAX Method

Video tutorial to read XML file using jQuery ajax method.

AJAX full form: Asynchronous JavaScript and XML
We’ll also see the use of setTimeout() function.

Using AJAX technique, we fetch only the required data from the server without reloading the entire page.

In this video tutorial, we fetch the data present in XML format and display fetched content on the webpage and update it in real time, without reloading the html page.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head><title>Reading an XML file using jQuery</title></head>
<body>
 
 <ul></ul>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 1 ul tag. We’ll load the list items dynamically using jQuery, from XML file.

XML File Content
corporateData.xml

1
2
3
4
5
6
7
8
9
< ?xml version="1.0" ?>
 
<corporate>
 <employee>
  <name>Satish</name>
  <age>25</age>
  <company>Microsoft</company>
 </employee>
</corporate>

Here we have a base tag called corporate. Inside that we have employee details like name, age and company which is bound inside employee tag. Each employee will have his/her details inside separate/individual employee tag.

For more about XML, please visit XML category.

jQuery File: corporateData() function
my_script.js

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
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
     });
}

Here we write a custom jQuery function called corporateData.
$.ajax() is a jQuery static method and it has a lot of properties. In this tutorial, we illustrate url, dataType, success and error properties.
Specify the url from which the data has to be fetched, along with its data type.
If the file gets parsed successfully, the function inside the success property gets executed. If there is an error, the error property function gets triggered.

Once the xml file gets parsed successfully, $.ajax method throws an object which contains xml file data. We catch this data with anonymous function present in success property.
Next, we clear any previous data got attached to the unordered list of html document.

Using the object, we find each employee tags present inside the XML file, fetch individual name, age and company names and then append it to the unordered list.

jQuery File: setTimeout() method
my_script.js

1
2
3
4
5
6
7
8
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}

Inorder to make sure our application fetches the fresh data from the XML file, we check the XML file after certain period of time.
Using setTimeout() method of jQuery:
setTimeout() takes two parameters, first one being the function names to be called and the second one being the time interval after which those functions has to be called.

using setTimeout() we have called itself( fetch() ) and corporateData() function. This makes sure, whenever the XML file gets updated, our application fetches the data and displays on our webpage, without refreshing the page.

jQuery File: call the functions to make it work
my_script.js

1
2
3
4
$(document).ready( function() {
 corporateData();
fetch();
});

Make sure to call both corporateData and fetch method once the page loads. This makes sure the XML data is fetched before fetch functions tries to re-fetch the things.

jQuery File: Complete Code
my_script.js

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
31
32
33
34
35
36
37
38
39
$(document).ready( function() {
 corporateData();
fetch();
});
 
function fetch() {
 
setTimeout( function() {
 corporateData();
fetch();
}, 100);
 
}
 
function corporateData() {
 
$.ajax({ 
 
 url: "corporateData.xml",
 dataType: "xml",
 success: function(data) {
 
  $("ul").children().remove();
 
  $(data).find("employee").each( function() {
 
   var info = '<li>Name: '+$(this).find("name").text()+'</li>
                       <li>Age: '+$(this).find("age").text()+'</li>
                       <li>Company: '+$(this).find("company").text()+'</li>';
 
   $("ul").append(info);
 
  });
 
 },
 error: function() { $("ul").children().remove(); 
                             $("ul").append("<li>There was an error baby!</li>"); }
});
}

corporateData.xml and index.html files must be in the same folder.

Video Tutorial: Reading XML File Using jQuery AJAX Method


[youtube https://www.youtube.com/watch?v=Dj3MP5w0dpc]

YouTube Link: https://www.youtube.com/watch?v=Dj3MP5w0dpc [Watch the Video In Full Screen.]



Note:
Make sure you open the html file from a server(even from localhost), and not directly from a folder. XML and the files which are fetching XML data must be on the same server, otherwise XML data won’t be fetched.

Testing The Application
To test this small application, open the index.html file from the server, and then add / modify / delete any entry. Once you save the XML file, the content of XML file must get updated on the html file immediately without the page(index.html) being reloaded.