Monday, November 28, 2011

Learn linux

If you want to learn linux and download some books on it visit Linux Tips

Linux OpenSUSE 12 Review

OpenSUSE 12 Review


Ubuntu Gadgets

I am using Ubuntu so I found several usefull gadgets for your desktop.


The clock, weather and the calendar are the most I use :)

Linux Mint 12 Review

If you are a Linux fan like me, here is a Linux Mint 12 Review


Wednesday, November 23, 2011

Database solutions for PHP

In this post I will explain the most popular and most used database engines capable of working with PHP.  They are many, and have different capabilities and architectures. Some of them are payable and expensive, some of them are open source. So depending on your needs you can use some of the great variety of database engines. No matter which one you use PHP has prebuilt drivers and PDO libraries for the all of them.

Here is a short list:
1. SQLite (open source)
2. MySQL (open source)
3. PostgreSQL (open source)
4. dbm-style databases (Oracle Berkeley DB)
5. Oracle Database (payable), Oracle XE (open source)
6. ODBC

1. SQLite

Although you might think that MySQL is most popular when working with PHP, you are quite wrong. The most popular db engine is SQLite. It is so popular because it is small, reliable and also embeded database engine. When you develop application that uses SQLite it is by default embeded inside the application that uses it, for example Firefox, Skype, mobile platforms like Symbian, iPhone etc. In the newest version of PHP SQLite is bundled with it so you don't have to install anything additional. It is fast and supports the SQL standard commands. It is simple because it is not structured like client-server and the code is open source so you can use it and modify it to your needs.

Some of the features of SQLite:

 - Dynamically typed: Given field can hold different types of data from one record to the next, much like a NoSQL database. This is very useful when working with PHP since it is loosely typed language. The drawback is that it is hard to maintain db integrity and it is not compatible with other db engines.

- Given database is stored in a single cross platform db file. So you can easily use the same db with other application that works with SQLite.

- It is easy to configure because there is no need of installation and no need to create users and add persmissions.

- You can call PHP commands from within an SQLite SQL query. So when working with some query you can call PHP function within the same query and it will surely work well.

MySQL is most known by PHP developers so I will jump right to 3.

3. PostgreSQL

PostgreSQL is also open source db engine much like MySQL. In fact the closest relative to MySQL is PostgreSQL. They both support the same capabilities and work at the same level of scalability. MySQL is known for its ease of use and great speed, while PostgreSQL is known as feature rich and reliable. But as the time passes both of them became powerful enough and surpassed their disabilities. You can access PostgreSQL with extension and also with PDO driver much like MySQL. So after this you can use both, as they are both good. It depends on your flavour which one to choose.

4. dbm-style databases (Oracle Berkeley DB)

 dbm-style database is an embeded type of db developed in 1970s. It is like SQLite but not nearly powerful. It stores files on the hard disk and it doesn't use SQL commands. But it can be very fast as records are taken with only a given key. This type of dbs aren't used very much today but the most popular of the existing is Oracle's Berkely DB.

5. Oracle Database and Oracle XE

Oracle is a company most well know by the database software systems that it develops. Oracle databases are used mainly in large organisations and companies that have a need of complex queries and store large amounts of data. Thus it is very expensive to use. So if you need small scale db engine for a low traffiic application than you should use the above given or Oracle's XE edition which is open source. For use with PHP you can use OCI8 extension or PDO driver.

6. ODBC

ODBC is not a database engine but it is an API interface for accessing and working with several db engines like MS Access, MS SQL server, and IBM's DB2 engine. MS Access and SQL Server are only available on Windows systems so this would be good solution if you work on Windows. As for DB2 there are AIX and, Unix, Linux and Mac as well as Windows.

Windows has preinstalled ODBC driver but there are open source drivers for other platforms like Linux, Unix and Mac OS X.

Ok so this would be all about PHP compliant db engines.

used literature from Beginning PHP 5.3 by Matt Doyle

Sunday, October 16, 2011

HTTP responses

When the web server receives the request it processes it and sends back HTTP response. The HTTP response doesn't differ very much from the request. It contains the data requested from the browser and also additional info about the message itself. HTTP response is structured like the response with 4 parts:

1. Status line - This tells the status of the request, whether was bad or good or an error happened.
2. List of HTTP headers - Headers give additional info about the message, like the type and the length of the message.
3. Empty line - This is an empty line between the status line and the headers.
4. Message body(optional) - This part contains the returned web page or maybe other web resource like image or stream.

Here is an example taken from http://web-sniffer.net/

Status: HTTP/1.1 302 Found  
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=40bebf53f84a37a4:FF=0:TM=1318795218:LM=1318795218:S=Uj37tfkySeEueQGz; expires=Tue, 15-Oct-2013 20:00:18 GMT; path=/; domain=.google.com
Date: Sun, 16 Oct 2011 20:00:18 GMT
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
Connection: close

<HTML> 
 <HEAD> 
   <meta http-equiv="content-type" content="text/html;charset=utf-8">
   <TITLE>302 Moved</TITLE> 
 </HEAD>
 <BODY>
   <H1>302 Moved</H1>
      The document has moved
      <A HREF="http://www.google.de/">here</A>.
 </BODY> 
</HTML>
 
So the status line contains the given status of the status of the message. There are several most 
important statuses that can be acquired by the browser:

200 - OK - Browser request was successful, follows the returned content.
301 - Moved Permanently - Requested resource is at different location, new URL will be returned in the 
Location header. Browser should use new URL 
302 - Found - requested resource is temporarily at new URL, new URL will be returned in the Location 
header. Browser should still use the same URL. 
400 - Bad Request - Request sent by the browser was invalid. (example: wrong syntax)
403 - Forbidden - Browser accesses web resource that has no permission to. For example browser
 tries to access file that is password protected.
404 - Not Found - Requested resource cannot be found on the server.
500 - Internal Server Error - Problem occurred while processing the request

Now about the response headers. There are several most important response headers that a web 
server can return:

Date - Date and time of the response 
Content-Length - Length of the returned contents in bytes.
Content-Type - MIME type of the contents that follow.
Location - Alternative URL of the requested content, usually used with 301 and 302 status codes.
Server - Info about the web server, like type, name and version
Set-Cookie - Request that an cookie be set on the requesting browser.

One web page can have several other resourses connected to it like, javascript files, css files, 
php file etc. So when one page is requested, usually several HTTP requests/responses will be 
done in order to display the whole web page. 

HTTP requests

HTTP stands for Hyper Text Transfer Protocol. It is a part of the TCP/IP network stack i.e part of set of several networking protocols like, TCP, IP, SMTP, FTP, ICMP, IGMP and others. It used as a main protocol for exchange of hypermedia contents like web pages, video, audio, images and also file sharing. So every computer system that sends request with HTTP to the server acts like a HTTP client and the system that returns response is called HTTP server. Usually the browser (Firefox, IE, Crome) is the HTTP client and as a server it is Apache HTTP server (also Glassfish for Java, IIS for .NET and php).

Every HTTP request consists of 4 parts:

1. Request line - this part of the message tells the web server which resource (URL) the browser has requested, i.e which web page or video/audio should the browser display.
2. List of HTTP headers - HTTP headers are additional info for the resource and how the browser should display the resource. In headers there is an info for cookies, character set of the page or to which page to redirect the user.
3. Empty line - An empty line between the request line and the headers.
4. Message body (optional) - This part of the request message may contain additional data for example data from given form sent via the POST method.

Note: Every line in the HTTP request message should end with carriage return character followed by line feed character, i.e must end with "enter" which ends the line and starts new line.

Here is an example of a given HTTP request message taken from http://web-sniffer.net/  . You can try it yourself

Connect to xxx.xxx.xxx.xxx on port 80 ... ok


GET / HTTP/1.1[CRLF]
Host: www.google.com[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)[CRLF]
Accept-Encoding: gzip[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
Referer: http://web-sniffer.net/[CRLF]
[CRLF]
 
 The request line consists of three parts: 
1. Request method - In this case it is GET, but it can be POST, HEAD, PUT, DELETE, TRACE, 
CONNECT etc. Visit wikipedia page for more info at HTTP.
2. The url to the resource - in this case it is forward slash("/"). We don't know the index page for 
the www.google.com so the server resolves on its own. Usually it would be something like /index.php.
3. The version of the HTTP protocol - In this case it is 1.1 which is default for most modern browsers.  
 
Follows a list of the most common HTTP headers that can be sent via HTTP request

-------------------------------------------------------------------------------------
Accept - List of MIME types that a browser will accept with the returned content.
Example:  Accept: text/html, application.xml, ...
-------------------------------------------------------------------------------------
Accept-Charset - a list of charsets that the browser will accept with the returned
content. Example: Accept-Charset: ISO-8859-1, utf-8
-------------------------------------------------------------------------------------
Accept-Encoding - a list of compression methods that the browser will accept from
the response. Example: Accept-Encoding: gzip,deflate
-------------------------------------------------------------------------------------
Accept-Language - a list of languages that the browser will accept from the recieved
content. Example: Accept-Language: en-gb, pt-br
-------------------------------------------------------------------------------------
Cookie - HTTP cookie sent by the sending server. Example: Cookie: name = John, 
surname: Doe.
--------------------------------------------------------------------------------------
Host - The Host header is the only mandatory header. It is mandatory because most
modern web servers can support several websites on the same machine, Host header
is needed to resolve from which web site the web server should send response to the
browser. Example: Host: www.google.com
-------------------------------------------------------------------------------------
Referer - Referer is the referers URL. Web servers constantly log from which web
page, given new page has been visited from. So the referers url is the url of the page
that the new page has been accessed from. Example: Referer: www.web-sniffer.net
------------------------------------------------------------------------------------
User-Agent - It holds info about the browser such as the type and current version.
Example: User-Agent: Mozilla/5.0 ...Gecko/xxxxxxx  Firefox/3.0.5 
------------------------------------------------------------------------------------

So this was mainly for the HTTP requests. In the next post I will explain the HTTP responses the same
way as requests.

Wednesday, August 31, 2011

JQuery basics

In this post I will explain the basics of JQuery, what it is and what it is used for.

JQuery is cross browser javascript library that is easy to learn and easy to use. It has two versions one is for production which is compressed (about 31KB) and other which is not compressed (about 230KB) and is for development. So when developing or learning you should use the development version and when you are publishing some website use the production version.
JQuery is written by several IT proffesionals whose main mission is to make JQuery the best javascript library for web.

You might wanna visit JQuery .
There are several other good javascript libraries like prototype, scriptaculous, Google Web Toolkint, and many others list of js libs. What makes JQuery so popular is that it is cross-browser, CSS3 compliant, easy to learn and to use. It has a wide variety of tools built on it like widgets, interactions, utilities, special effects.
For example implementing simple accordion with text data is no more than writing div tags and importing js files in your html.

I will be writing some tutorials on using JQuery with AJAX, implementing widgets like accordion, slider, progressbar etc. so make sure you have Firefox with firebug installed or maybe Chrome. About IE I haven't used it much so maybe I will make some tut on it in future.

Tuesday, August 30, 2011

Structure of the Sakila database

The sakila database contains 23 objects of which 7 are views and 16 are tables.

You can open MySQL workbench and choose the "Open Existing EER Model" for the sakila diagram option in the Data Modeling section. The EER diagram will show up. This database is for storing movies data.

So we have film table which contains film data and also

which language it is filmed in,
which list of actors have acted in it,
which category of film it is
and in which inventory it has samples.

Than we have customer table which stores data about the customer and also

from which country the customer is,
in which city and address he lives,
which file does he rented and when he needs to return the movie.

Also sakila stores data about payments and the online store.

Now there are 7 view which are:

1. sales by film category,
2. Sales by given store if we have several
3. Info about given actor,
4. customer list
5. films list
6. staff list
7. all films list, which is bigger and gives result slowly.

Now that is rough view of the sample sakila database. Hope that this is helpful.

You might wanna visit the sakila official page at Sakila

Basic PDO commands to access and manipulate MySQL database

Ok. Now that we have PDO and sakila sample database installed we can begin writing our first code of accesing and showing database data.

Open Netbeans and open the HelloWorldPHP project that we hava in early posts created. Open the index.php file in the editor. Now we need to create connection to MySQL if we want to use the sakila database.

first we write try, catch block and write out our connection strings:


$hostname = "localhost";
$usernameMySQL = "root";
$passwordMySQL = "root";


try{
     ////connection code
}catch(PDOException $exp){
     /////exception code
}

In my case username and pass to MySQL are root, root
Ok so the connection code would be this:

$pdo = new PDO("mysql:host=$hostname;dbname=sakila", $usernameMySQL, $passwordMySQL);
echo "I have succesfully connected to database";

We create $pdo object which gets three parameters: name of the host and type of database driver. In my case that is localhost and mysql. So it can be other host name if the database is hosted on remote server. For dbname we write sakila the name of our db.

The exception code would be this:

 echo $exp->getMessage();

Exception code writes the error message that was took when error occured while connecting.Try, catch block is useful in cases we want to redirect the user to an error page when some error occurs, in our case we would make error page and write some text in it to notify user that there is a problem. So now my index page looks lie this:
            

$hostname = "localhost";
$usernameMySQL = "root";
$passwordMySQL = "root";
         

try{
            $pdo = new PDO("mysql:host=$hostname;dbname=sakila", $usernameMySQL, $passwordMySQL);     

       echo "I have succesfully connected to database";
}catch(PDOException $exp){           
       echo $exp->getMessage();
}
         

Now that we have successfully connected to MySQL we need to prepare some SQL statements in order to use sakila db data. 

In the try block below the echo statement write this code:

$sql="select title from film";
$stmt=$pdo->prepare($sql);
$stmt->execute();
$filmTitles=$stmt->fetchAll();


We are creating sql statement to select only the title column of the film table.
After that we prepare the sql and return the result to the $stmt variable, short for statement.
Than we execute the sql on to the database.
In the last command we fetch  all table entries that the sql statement returns and put them in array $filmTitles

Below the code for the sql write this code for printing the fetched data:

echo "<table border='1'>";
echo "<tr><td>Film Title</td></tr>";
for ($i=0;$i<sizeof($filmTitles);$i++){
                echo "<tr><td>".($i+1).". ".$filmTitles[$i]['title']."</td></tr>";

}
echo "</table>";

No we parse trought the fetched data with for cycle. $filmTitles is an array of arrays with two elements i.e it is 1000x2 matrix. So we access each element with this code $filmTitles[$i]['title'] and we can see that the subarrays are associative. You can use print_r function to print the data in filmTitles and see whats behind the hood.


Try this in your php code after the for

print_r($filmTitles); 

 This is the basic setup for PDO data access to database. More tuts on this to come :)

Sunday, August 7, 2011

Installing PDO on Ubuntu

Requirements for this post:

Installed php 5.1+ engine, apache2 web server
installed Netbeans 7 or 6.9
Installed MySQL and MySQL WB.

If you havent already installed this visit my older posts and install whats missing.

So in this post I will explain what is PDO and how can be installed on Ubuntu/Windows.

PDO stands for PHP Data Objects. It is PECL extension for PHP 5.0 and ships with PHP 5.1 and newer versions of PHP. It is dependent on OO features of PHP so it will not work in older PHP versions.

It is data-access abstraction layer  which means that you can use same function for access and manipulation of db data no mather what type of db is behind. So depending on the type of the db behind, you use special PDO driver for that database.  Here is the official PDO docs PDO .

PDO is not dependent of other libraries and extensions so if you have PHP 5.0+ you are ready to go and install.

PDO is a PECL extension so you will need this package in order to install pdo php5-dev.

Open terminal and run this command:

$sudo apt-get install php5-dev

 No we will install PDO.

The easiest way to install on Ubuntu is to use these commands:

$ sudo apt-get install libmysqlclient15-dev
$ sudo pecl install pdo
$ sudo pecl install pdo_mysql
 
 I have PHP 5.3 so no need to edit the php.ini file. If you have other version 
you should edit the php.ini file and add these lines 
 
extension=pdo.so
extension=pdo_mysql.so
 
On PHP 5.3 php.ini is place in the /etc/php5/apache2 folder. 
On other PHP versions it should be in /etc/php5/cgi/php.ini or /etc/php/cli/php.ini.
 
So no open terminal and run this command 
 
$ sudo gedit /path/to/php.ini 
 
mine was 
 
$sudo gedit /etc/php5/apache2/php.ini
 
It will open text file. Find the Dynamic extensions section and add the lines
 
extension=pdo.so
extension=pdo_mysql.so 
 
Now save the file and close it. In terminal run 
 
$ sudo /etc/init.d/apache2 restart 
 
to restart the web server.   Now I will create a test project in Netbeans to test 
the installtion of PDO. 
In previous post I created new PHP project called HelloWorldPHP. If you haven't 
I will explain it again here. 
Open Netbeans and click file->new project. Choose new PHP application 
and click next. Add the name of the project HelloWorldPHP and place it in the 
sources folder /var/www/HelloWorldPHP. Click finish. This will open new 
project in the projects panel. 
 
Now, click right click on the  HelloWorldPHP node and click 
set as main project. Open the sources folder and double click the index.php file
It will open in the editor window. Now you will see a php segment 
 
<?php ?>
 
Add this line of code phpinfo(); 
 
Your page will look like 
 
<?php phpinfo(); ?>
 
 
Now open a browser and type this url: http://localhost/HelloWorldPHP/ 
or click run->run main project in Netbeans. You  should get the php info 
page with all settings. Now far below on the page you have to find PDO 
section and pdo_mysql section. If this is the case than you installed it succesfully. 
Otherwise check what's wrong and post a question. 
 
In the next post i will add some on installing PDO on Windows.

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