Friday, July 29, 2011

Installing Sakila sample database

Ok, so in this post I will show you how to install Sakila sample database on our MySQL server by using Netbeans IDE. So make sure you install Netbeans and all other necessary software for this to work. You might wanna visit Installing Netbeans or LAMP Installation .

Ok so now open Netbeans 7 or other version if you have and got to tools->plugins .

Now new window opens. In the Available plugins tab find and select "sakila sample database". Cliks Install. Accept the terms of agreement and click next.

The sample database installs. Ok so now open the services tab in the left panel where Projects and files tabs reside. Click the databases tree. You will see sub tree called " MySQL Server as localhost:3306[root] ". Right click on the entry and click create database. In the dropdown list select Sample database sakila. It will ask you whether you want to install the sample database on MySQL. Click yes.

Wait a moment and the database is installed with its own data.

Now open MySQL workbench and double click on the mysql connection. New window opens. You should see the Sakila database in the left panel. Thats it. I will use this sample database to explain some advances topics of php and how to manipulate data on MySQL server.

You might wanna visit Sakila on Netbeans .

Quick description of the Sakila database:

It is successor of a previous sample database called World. So it is improved and enriched. It has several tables,views , triggers and stored procedures in order to begin learning advanced work with databases.

Monday, July 18, 2011

Installing Netbeans 7 and JDK on Ubuntu

So we installed the needed software now we need a comprehensive IDE editor for developing php applications. I use Netbeans because it has support for PHP. 

You can also use Eclipse as an alternative by installing PHP plug-in. You can also use the adapted to PHP Eclipse version called Aptana. It has predefined PHP plug-in and also debuger. You can get it at this page aptana studio

Now before we install Netbeans or Eclipse we need jdk preinstalled on Ubuntu. jdk stands for Java Development Kit and is the needed environment for Netbeans/Eclipse since they are developed as Java applications.

So now go to this page java downloads. Since we are installing on Ubuntu download the second option with no RPM in it. The package with RPM is for Fedora and RedHat Linux distributions. You will download a bin file.

After the download run terminal and browse to the downloads folder of your system where you downloaded the bin file. 
Next, type this command:

$ chmod a+x jre-6u-linux-i586.bin

Now replace the with the version of the jdk you downloaded. This will make the file executable since it wasn't. If you get any error you also use this command:

$ chmod 777 jre-6u-linux-i586.bin

Now run this command

sudo ./jre-6u-linux-i586.bin

This will now install java development kit on your computer. After this finishes we are ready to install netbeans.

Note: Eclipse is a java base application it doesn't need to be installed like netbeans. Just download extract and you are ready to use it without installation.  You might wanna visit this page for eclipse eclipse downloads. Now it is preety much handy to create a shortcut to you desktop and also create menu item in you system menu(In other post).

Now we will install Netbeans 7.0 . Go to this page netbeans downloads and download the package that has dot in the php row. This package has preinstalled plug-ins for php, zend framework and also other stuff. No you will get an *.sh file. When download finishes open terminal and go to the downloads folder.

Run this command:

$ sudo chmod +x name_of_netbeans_file.sh

This will make it executable file. Now run this command 

$ sudo ./name_of_netbeans_file.sh

This will now install Netbeans on your system.

Note: For windows systems choose the windows option and download and install the ms installer for netbeans.

Wait a while and after the install is finished got to the system menu -> programming -> Netbeans IDE 7.0 This will start the IDE. We will create an empty test project with these commands:

File->New Project ->PHP Application.

In the Name and Location dialogue window place the name of project "HelloWorldPHP" and in the sources folder there must be /var/www/ in from of the HelloWorldPHP, so your location would be /var/www/HelloWorldPHP. In the next steps leave all fields default and click finsih.

That's it you created your first PHP application in the Netbeans IDE.

Before you work on this post see first ubuntu installation

Saturday, July 16, 2011

Basic quickstart commands on MongoDB

In this post I will explain the basic commands for inserting, retrieving, limiting the data sent from/to the database.

Ok so now we have inserting data to the db.

go to /bin folder and type mongo. The shell appears.
Now type insert these three documents:


> db.movies.save({title:"Harry Potter",year:2010, duration: "120 min"});
> db.movies.save({title:"Expendables",year:2010,duration:"140 min"});
> db.movies.save({title:"Green Lantern",year:2011,duration:"150 min"});


We are creating collection called movies and add three documents for movies. (Note: The data here is maybe not correct, it is just for example). So these commands corespond to the SQL statement

insert into movies (title,year,duration) values ("Harry Potter", 2010,"120 min");
insert into movies (title,year,duration) values ("Expendables", 2010,"140 min");
insert into movies (title,year,duration) values ("Green Lantern", 2011,"150 min");

 Now use this command

> db.movies.find();

This will list all documents in the movies collection. Now we will create a script with for statement.

> for (var i = 1; i <= 25; i++) db.script.save({blog:"TunePHP", j : i});
 
This script will create a collection called "script" and add documents in the format 
{blog:"TunePHP", j : i}
 
run > db.script.find(); 
 
Now the limit of the find command is 20 rows. In case where there
are more than 20 documents in a collection we use the it command. So now in terminal run
 
> it 
 
it will show the rest docs in the script collection.

Installing MongoDB

I use MongoDB on Ubuntu but you can also use it on Windows. I will explain how to install it on Ubuntu.

I installed myselft with oppening terminal and typing:

$ sudo apt-get install mongodb

Wait a moment and it will be installed. There is an option to build it from binary sources but this is much more complex (In other post).

Next, you must create directories for the db so open terminal and type in these commands:

$ sudo mkdir -p /data/db/
$ sudo chown `id -u` /data/db 
 
This creates folder data/db at root level and change owner to root. 
Now you should be able to use MongoDB. Start the server by typing in terminal:
 
$ sudo start mongodb  or this $ service mongodb start. You will get a message 
whether the service is started. If it is started than go to this folder /bin and type  
mongo in terminal i.e
 
$ cd /bin
$ mongo    you will get the ">" char in terminal so it means it works.
For start type in 
 
> use mydb 
> db.testcol.save({json : "this is a json object"});
> db.testcol.find();
You should get something like this as output:
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "json" : "this is a json object" }
 
With these commands we use the database called mydb and than create a collection 
(table) called testcol and save one BSON document (row)  
{json : "this is a json object"}. The find command prints all document in the collection  
testcol. You should visit the SQL to Mongo Mapping page at SQL-Mongo
 
You can notice that we use json notation to create documents (rows) in the database, 
Mongo works its way i.e it constantly converts from json to bson and vice verse. 
 
I will add some examples on how to work with Mongo so make sure you read well 
about json.  
 
 You might wanna visit the downloads page @ downloads
Select you operating system version and download it.  Also visit Quickstart

Intro to MongoDB

Drupal with MongoDB

Mongo-DrupalHere is another slideshare presentation on drupal CMS 
View more presentations from Forest Mars

Slideshare presentation - PHP to MongoDB

PHP, Lithium and MongoDBRead this presentation and post some questions/comments. This is just for start, will add some content soon.  
View more presentations from Mitch Pirtle

Thursday, July 14, 2011

Understanding BSON

BSON stands for Binary JSON. The difference between JSON and BSON is that BSON is like binary representation of JSON document or more like serialization i.e to convert JSON document to serialized document with some extra characters. This way BSON supports data structure types that are not available in JSON, like BinData type.

BSON is lightweight, traversable (used in MongoDB), efficient.

BSON in many cases has larger size than JSON document so why should we use it?

Well it the main goal for this is the traversability i.e faster processing. When creating BSON document in the code some extra data is added like length prefixes so that it is much more easier to decode it. Also integer numbers are stored as 32 bit integer so that there is no need of processing text . Thats why it is much faster but it takes more place.

You might wanna visit BSON . Also visit the specifications page. 

In the next post I will talk about implementing the MongoDB and installing php drivers.

Example for converting xml document to JSON

We have this example of xml

<menu id="file" value="File" number="50" >
     <popup>
        <menuitem value="New" onclick="CreateNewDoc()" />
        <menuitem value="Open" onclick="OpenDoc()" />
       <menuitem value="Close" onclick="CloseDoc()" />
     </popup>
</menu>

So I will shortly explain the alghorithm to convert xml to 
json code. 
Every json document starts and ends with curly 
brackets {}. Next, menu is a top level tag and contains several 
other subtags so menu is an object. Atributes in the menu tag 
are name/value pairs so in the first step we have this:
 
{
  "menu" : {
  "id" : "file",
  "value" : "File",
  "number" : 50,
  "popup" : ...
}
}

Note that numbers aren't quoted only strings are quoted.
 
Next we will develop the popup and menuitem tags. popup has 
several tags in it so it is an object. Also there are three 
menuitem tags so we need to make an array of them. But also 
every menuitem has several atributes so every menuitem 
is also an object.

We get this:
"popup": {
    "menuitem": [
                {"value": "New", "onclick": "CreateNewDoc()"},
                {"value": "Open", "onclick": "OpenDoc()"},
                {"value": "Close", "onclick": "CloseDoc()"}
    ]
}
We will connect both above examples and now we get this: 
{
"menu": {
    "id": "file",
    "value": "File",
"number" : 50,
    "popup": {
      "menuitem": [
        {"value": "New", "onclick": "CreateNewDoc()"},
        {"value": "Open", "onclick": "OpenDoc()"},
        {"value": "Close", "onclick": "CloseDoc()"}
      ]
    }
  }
}

Wednesday, July 13, 2011

Intro to JSON

In this post I will talk about JSON and its basics. Since it is a main notation language to work with MongoDB.

JSON stands for JavaScript Object Notation.

Like XML JSON is a data interchange format, it is readable by humans and in some aspects better than xml. For example it is more compact and it saves traffic because it has small size whereas xml file can get very large and heavy to transfer over network.

JSON is completely language independent but it is developed on many language concepts that exist in C/C++, python, Java, Javascript, Perl etc...

JSON has two data structures built in.

- Collection of name/value pairs. In other langs this type of collection is realised as  object, record, struct, dictionary, hash table, keyed list, or associative array.

- Ordered list of values. In other langs this is an array, vector, list, or sequence.
These two data structures in JSON can get the form of: object, array, string, value and number.

- Object is an unordered set of name/value pairs. Object begins with "{" and ends with "}". Each name/value pair is separated with other pairs with "," and between name and value always stands ":".

example: object {
                      myName:Vlad,
                      myBlog:tunephp.blogspot.com
               }

-  Array is an ordered collection of values. Array starts with "[" and ends with "]". Values are separated by ",".

example: array[val1,val2,val3]

- Value can be of type string, number, object, array, true, false, null
- String can be any type of string like in other langs.
- Number is a usual number like in other langs (C, Java) except that octal and hexadecimal aren't used.

You might wanna visit the official site JSON . Also dont forget to visit the examples at JSON Examples

Intro to document-oriented databases

In this post I will explain the basics and advantages of the document-oriented databases over relational dbs.

Document database is a database constructed of documents that has its own structure and can be independent from each other i.e there is no need of relations like in RDBMS.  There are no tables, rows, relations at all. So when I want to add new field in the database I simply select a document and add it without the need to update and affect other documents in the db.

DO databases are called semi-structured dbs because they don't have the need of a predefined schema like in RDBMS.

For example if I have one document that have these fields: name, surname, proffession, phone, I can create document by filling all fields except the phone field which can be empty and it will not be kept as null but it will simply do not exist. But I can also add new field which is not in the above list for example email and give it a value of my email.

Below is a list of the advantages over RDBMS:

Objects are stored as documents. So now we can use the serialize method in a language to convert object to a document and save it to the db.
- Documents can be of any complexity. Objects model can be read and written at once. NICEEEEEEE :)
In this case we are relieved of the need to think of complex sql statements and stored procs.
Documents are all the way independent. This is good for performance and the side effects of concurrency are decreased
- Formats for accessing and using DO dbs. The documents in the dbs are described with JSON, XML and derivatives like Binary JSON
- Schema free. This ability gives us flexibilty to sturcture the data inside without the need to restructure it again after some time.
Built-in verisoning. DO databases can support versioning of documents and it can be done with several clicks

The DO dbs can be sorted in these categories Document, Graph, Key/Value, and Tabular/Wide Column.
 All of them with its own advantages and drawbacks.

The most popular products that declare themselves as DO dbs are:

- CouchDB
- RavenDB
- MongoDB

So where these dbs would best fit in? Well DO dbs are good for CMS and CRM systems where the user usually wants to customize his data and this is easy with saving documents. Also DO dbs would be useful in creating and storing data from a shopping cart and user sessions.

In the next posts I will try to explain briefly the above given products and their properties.

Tuesday, July 12, 2011

$GLOBALS

$GLOBALS is a super global variable and it is structured like array. Well most of the superglobals are asociative arrays. It contains all user defined variables that are accesible in the global scope.

Here is an example

<?php

$var="Hello";

echo $GLOBALS["var"];
//it will print Hello

function varFunc(){
      $var="Hello world!";
}

varFunc();

echo $GLOBALS["var"];
//it will still print Hello
//Why? Because $var located in the function is a local variable and is //inaccessible. 
?>

About predefined global variables in PHP

One thing that makes PHP so flexible and easy to use is that it has several predefined variables which are global and accessible from whichever PHP script you write.

Here is a complete list of them:


    You can get a full reference of them on this page superglobals
    The most commonly used are these: $GLOBALS, $_POST, $_GET, $_REQUEST, $_COOKIE, $_SERVER and $_FILES. So I will explain these in different posts and show some examples.

    Configure installation on Ubuntu

    There are several stuff that need to be configured in order to develop with php.

    Firstly when installing MySQL server you will be prompted for password. Usually the default user is named root and I usually give him a password "root" but you can place your own. My recommendation is to create new user on MySQL and use the new one with php development. But its up to you (you can use phpMyAdmin or MySQL WB for this).

    Ok so next thing is to get up and running phpMyAdmin. By default It is not configured ad running so we will do this:

    Open terminal and run this:

    sudo gedit /etc/apache2/apache2.conf

    when the apache2.conf is oppened got to the bottom of the page and add this line:

    Include /etc/phpmyadmin/apache.conf

    After this run 
    sudo /etc/init.d/apache2 restart

    to restart the apache. Now open firefox and type the address http://127.0.0.1/phpmyadmin. The login form should appear. Enter the username and password for the root user and you will enter the world of MySQL database server. 

    The next thing to configure is MySQL WB.

    If you have already installed MySQL WB we will set up a basic conection to our mysql server. Open MySQL WB and click new connection. New dialog windows should open. Leave all settings to default and type in the connection name. In my cas i will name it mysql. Also it is helpful to store the root's password in key chain for future use. So press the store in key chain and enter the roots password. This will remember the password so you will not have to reenter it again. That's it, press Test connection. If you get that connection parameters are good than your conn is good and ready to be used. Press ok.  New windows will open and you will see the existing databases on the left panel.

    Installation on Ubuntu

    Well there are several stuff you need to do in order to start developing php applications.

    This is the necessary software for php on Ubuntu:

    1. php5 engine

    2. apache2 server

    3. mysql database server

    4. phpMyAdmin and MySQL Workbench.

    I am using the separated installation of the software because I think it is easiest to manage. How ever you can use the xampp installation for linux. It will install everything in one go. Here is the page  xampp.

    Ok. So now open terminal on linux and type this command:

    sudo apt-get install php5 apache2 mysql-server phpmyadmin

    and enter your linux user password.

    This will install all 4 parts of the above software except MySQL WB which we will install manually. I will use MySQL WB in my posts because it supports some things phpMyAdmin doesn't. But that doesn't mean that phpMyAdmin is bad. It is browser based database admin tool so some thins are not supported like MySQL WB desktop environment.

     Ok so now we will install MySQL WB. Got to this page http://wb.mysql.com/ adn click download. It will redirect you to the downloads page. Go down and choose the Operating System version. In our case it will be Ubuntu Linux. Select the 32 or 64 bit version and click download. If you already have mysql account log in and select a mirror (choose the nearest one to your location). If not create new one and than download.

    I downloaded this file mysql-workbench-gpl-5.2.34-1ubu1010-i386.deb. Go to downloads folder with terminal and run this command

    sudo dpkg -i your_package_name.deb

    Mine was

    sudo dpkg -i mysql-workbench-gpl-5.2.34-1ubu1010-i386.deb

    This will install it on your ubuntu and you can see it in the programming menu.



    You might wanna visit the Netbeans installation post at netbeans installation.

    The basic concepts

    Why do we call PHP scripting language?

    Wll you write scripts in a file with php extension like example.php.

    PHP code can be embeded within html code in every place you like to do so.  Why is this possible?  Well php is a code that is executed on the server, not on the browser side. So php code is not necessary for the browser.

    We add php code with the following start and end delimiters:

    -end. Any code between will be considered as php code and will not be shown or either processed by the browser.

    Here is an example:
    Create a file called example.php and open it with notepad or any text editor and write this code

    <?php

    echo "Hello world!";

    ?>

    This will print Hello world in the browser.  But to execute this command we will have to install all necessary software in order this to work. Comming up next, Installation.

    For start, the basics of PHP

    The programming language PHP or PHP is a Hypertext Preprocessor is a scripting language mainly developed to create web pages and sites the fast and easy way. 

    He is developed on C/C++ platform so newly created extensions base on C/C++ can be easily added. Thats why today PHP is used for many more types of applications rather that just webpages. For example there are extension to develop OpenGL graphics with PHP commands :)


    The latest version was php 5.3 but something is whispering that there is ver. 5.4. Anyway I will work on ver. 5.3 and maybe  go to 5.4 in the future.

    Which is the advanced feature that that makes PHP so popular and wanted?

    Well  it contains large set of functions for doing different tasks, for example you can make validation of email with just one function and two parameters. As for other languages you have to think of creating regular expression in order to do so. So if you need a website PHP is the right choice for you.

    PHP has its own good API documentation which is available on http://php.net/docs.php

    Don't forget to use it whenever you need it. It is well structured and has lot of examples.

    PHP main site:

    http://www.php.net