Tuesday, May 28, 2013

Using MongoDB with CodeIgniter - NoSQL

MongoDB is document-oriented NoSQL database.

What is NoSQL?
NoSQL is a kind of database that, unlike most relational databases, does not provide a SQL interface to manipulate data. NoSQL databases usually organize the data in a different way other than tables.

NoSQL databases are divided into three categories: column-oriented, key-value pairs, and document-oriented databases.

SQL based relational databases do not scale well when they are distributed over multiple cluster nodes. Data partition is not an easy to implement solution when the applications use join queries and transactions.

NoSQL databases are not new. Actually, there were key-value pair based databases before relational database became popular.

What is a document-oriented database?

For document-oriented databases, a document is a data structure that has variable number of properties. Each property has a value that can be scalar (number, string, etc.) or a vector (arrays or objects).

You can see a document as an object or associative array like in PHP. To understand better this concept, here is the definition of a "person" document:
$person = array(
    "name" => "Cesar Rodas",
    "country" => "Paraguay",
    "languages" => array("Spanish", "English", "Guarani"),
Documents do not have a predefined schema like relational database tables. Documents can have multiple properties. Documents can also be grouped in collections. The term collection is used from now on distinguish from the tables used by relational databases to store records with a fixed number of fields.

Another important characteristic of documents is that they can have sub-documents. Sub-documents are used in the place parent-child tables used with relational databases.

MongoDB (from “humongous”) is a scalable, high-performance, open source NoSQL database. MongoDB is non-relational (no joins) so references (“foreign keys”) between documents are generally resolved client-side by additional queries to the server (“linking”).
MongoDB is a very interesting document-oriented database implementation for several reasons:
  • - It uses JSON, instead of XML
  • - It is fast, as it is written in C++
  • - Supports index definitions
  • - Provides an easy to use query interface, very similar to some database abstraction layers
  • - Supports operations with sub-documents
  • - Provides a native PHP extension
  • - Supports auto-sharding
  • - Supports map-reduce for data transformation

MongoDB and Codeigniter
There is one library out there - Alex Bilbi has a lib that works just fine and YES you can go almost like ActiveRecord. You can view by clicking below link.

CodeIgniter MongoDB Library

This is an active record inspired CodeIgniter library to integrate a MongoDB database into your application.
Installing this library is as simple and painless as installing MongoDB - really a piece of cake.

ref: http://www.phpclasses.org/blog/post/118-Developing-scalable-PHP-applications-using-MongoDB.html

Top 10 Wrong Ideas About PHP

PHP is often a misunderstood language by people that either love or hate it.

On one side there are developers that hate PHP apparently because they do not quite understand how it works. They do not respect PHP and prefer other languages. So they lose many opportunities to make good money from the PHP market, which has so many high paying jobs for qualified developers.

On the other side there are developers that love PHP but do not take full advantage of the language because they are not fully aware of all they can do with it.

This article attempts to clarify some of the most common wrong ideas that many developers have about PHP.

Top 10 Wrong Ideas About PHP
Here follows a list of some of more common wrong ideas about PHP. I just presented the top 10 that I find more relevant, but I could have even listed more. It is that 10 is just round number that people are used to find more frequently in top listings. :-)

  1. 1. PHP is not a compiled language (it is interpreted) 
  2. 2. PHP cannot do X (access memory, control hardware devices, or some unusual purpose) 
  3. 3. PHP cannot do something that can be done in language X 
  4. 4. PHP is only for Web development 
  5. 5. PHP is controlled by only one company (Zend) 
  6. 6. PHP documentation is bad or insufficient 
  7. 7. PHP projects are not reusable because they are not Object Oriented 
  8. 8. PHP is worse than Ruby On Rails, Python Django, X language Framework 
  9. 9. PHP is not good for high performance scalable Web sites or applications 
  10. 10. PHP developers are cheaper because they are not qualified

Ref: For detail explanation of above mentioned points, visit http://www.phpclasses.org/blog/post/155-Top-10-Wrong-Ideas-About-PHP-That-You-Should-Get-Right.html

Friday, May 24, 2013

How to check if query string present on URL using jQuery?

document.location contains information about the URL, and document.location.search contains the query string.
    // query string exists
    // no query string exists
You even don't require jQuery. You can do that using simple jQuery.

Thursday, May 23, 2013

How to choose a random value from an array using JavaScript?

Use the following pseudo code to alert a random values from given array using javascript.
var item_array = [1, 3, 4, 5];
var random_item = item_array[Math.floor(Math.random() * item_array.length)];

Create an array of your choice, then pick one element from the array. You do this by choosing a random number using Math.random(), which gives you a result greater than or equal to 0 and less than 1. Multiply by the length of your array, and take the floor (that is, take just the integer part, dropping off any decimal points), so you will have a number from 0 to one less than the length of your array (which will thus be a valid index into your array). Use that result to pick an element from your array.

Source: http://stackoverflow.com/questions/5708784/how-do-i-choose-a-random-value-from-an-array-with-javascript

How to get a random value from array in PHP?

If you don't mind picking the same item again at some other time then you can use following code:
   $items = array(1,5);
   echo $items[rand(0, count($items) - 1)];
It will display a random number from the elements of array. 1 or 3 or 5 or 1 .......

Tuesday, May 21, 2013

Saving image from external url using PHP

There exists several methods to save image from external url to the remote server such as cURL, combination of file_put_contents and file_get_contents. But the most efficient method is to use copy() function.
copy() - Makes a copy of the file source to dest.
  copy(string $source,string $dest)
  $source = Path to the source file.
  $dest = The destination path.
If the destination file already exists, it will be overwritten. Returns TRUE on success or FALSE on failure.
  copy('http://example.com/image.php', 'local/folder/flower.jpg');
Note: Make sure allow_url_fopen is on.
Read more on http://php.net/manual/en/function.copy.php for detail explanation.

Monday, May 20, 2013

5 Reasons Why Web Platform War is Over: PHP Won!

During Google I/O 2013 event a Google manager said PHP runs on 75% of the Web sites. So they decided to finally support PHP as in their AppEngine hosting service.

Google I/O is a event mainly for developers that Google organizes every year to present the latest developments of their products.This year Google announced a new language being supported in AppEngine, their so called "cloud" hosting platform. This time the new language was PHP. A Google manager for AppEngine explained that PHP is running in 75% of the Web sites. That explains why PHP support is the top most requested feature for AppEngine.

In reality there was never a Web platform war, at least for most PHP developers.

What happens is that PHP gathered so much popularity, that people that prefer other languages often engage in argument wars against PHP just because PHP popularity compromises the chances of their preferred getting more popular. So in the minds of the fans of those other languages, they are in a war against PHP.

With this announcement from Google, it pretty much killed the arguments of those that fight PHP. If there was a war, PHP won it. Lets get over it. Here is why.

 1. Google Knows Because They Crawl the Whole Web

Google is the top search engine company. Every day thousands of robots spider the Web to crawl and index Web site contents.

So for Google it is easy to crawl the Web and determine which language is used in each Web site. Most sites with PHP installed respond with an header like this: 
Server: Apache/2.2.8 (Unix) PHP/5.3.11
 Although it is possible that some PHP sites may omit the information that PHP is running on the server, most sites do not do this.

So if Google figured that 75% of the sites run PHP after crawling the whole Web as they have been doing for all these years, they are the ones that have the most accurate evidence of the overwhelming presence of PHP.

  2. Google Does Not Influence Web Developers so much

 Definitely Google is a very influential company to anybody using the Internet these days.

It is natural that if Google declares they use a certain technology, it is like an endorsement that may influence people to also use that technology.

I have always heard that Google search engine uses C++ and most other services use Java because of the scalability provided by Java Application servers.

When Google AppEngine launched in 2008, they announced it was only supporting Python. That was odd to me because Python was neither one of the traditional Google languages, nor a popular Web language like PHP.

When I realized that Guido Van Rossum, the creator of Python was behind the Google AppEngine project, it all made sense. Why would he give priority to any other language besides his own creation? It seemed like a personal preference, rather than one based on language features or market share reasons.

It makes sense that a company standardizes on certain tools or programming languages that their employees are more familiar or have more control, but when they think of products for their customers, companies need to pay attention to what the customers prefer.

Microsoft paid attention to their customers many years ago and started actively supporting PHP, so it was odd that Google was not doing it.

Later they added support to Java and even the Go language. That is OK, but given the overwhelming presence of PHP on the Web, what was keeping Google from supporting PHP?

When asked, Google employees gave the standard excuse that Google did not have the necessary resources. Right, a company that makes 100 million dollars a day, does not have resources to support a language that many customers want to use. Something was not quite right in that justification.

Many years ago I heard from a Googler (now ex-Googler) that inside the company there have been huge discussions to add PHP support to AppEngine because it was a huge market that they were neglecting, limiting the commercial success of the product.

Some friends of mine speculated that Guido Van Rossum was against it because PHP support would put Python in the shadow. That made sense but it was still a speculation.

Last December Guido Van Rossum left Google. So, if he was the main opponent of PHP support, after he left the PHP opposition would be gone, or at least the opposition would become much weaker.

Only 5 months after Guido departure, Google announces PHP support for AppEngine. So the speculation that the Python creator was preventing Google from adopting PHP may actually not be far from the truth.

Anyway, if in 5 years Google could not convince PHP developers to switch to Python and use it in AppEngine, I guess Google influence over Web developers is very limited after all.

Too bad for Google that they delayed PHP support for all these years. They could have lead the PHP Platform As A Service (PAAS) market so much earlier. Nevermind, better later than never.

  3. Wordpress is the Dominant Blog Platform (not Blogger)

 One of the reasons why PHP is so successful is due to killer applications like Wordpress.

Just last month I gave an interview to Khayrattee Wasseem of the 7PHP site on which I have explained that in my opinion the success and prevalence of PHP is tied to WordPress and vice-versa.
Wordpress is so extensible that nowadays it can be almost anything you want besides being a blog. There are plugins to turn it practically into anything you want from a Web site.

Wordpress code may not be very beautiful in the opinion of prude developers, but that does not matter. Even developers that preach for other languages use Wordpress. Isn't ironic, don't you think?

More than a software application, Wordpress is an ecosystem, a way of life. Many people developers live exclusively from developing sites based on Wordpress. I see that here every day in the PHP jobs section.

The same could be said to a certain degree about Drupal, Joomla and other popular PHP applications. It is just that Wordpress is much more popular.

The Wordpress community seem to live in a world of their own apart from the regular PHP world. They organize their own events. Those events are always very crowded. I suspect that Wordpress events are even more crowded and frequent than regular PHP events. That says a lot about the importance of Wordpress to the PHP popularity.

  4. Programming Does Not Have to Be Beautiful

 Many years ago I started seing people praising Ruby On Rails as the best way to develop Web applications, as opposed to use languages such as Java or PHP.

I have seen talks from its creator David Heinemeier Hansson on which he was preaching that programming had to be beautiful. I wondered what that meant. Was it the coding style? The project architecture? The development methodology? Something else?

Maybe I missed the point but I assumed that Ruby On Rails imposes a certain methodology as the only way to do it right and be productive. If you do not get out of the rails you train can travel very fast.

It seems to me that using a certain methodology consistently does not require that you use a specific language or a specific framework to be productive.

I use the same methodology to develop PHP projects for years. I feel very productive because I follow the same methodology very consistently. I develop my projects really fast because work becomes mechanic.

It seems that Ruby On Rails brought consistency to the development of Web projects of people that did not know what method they should follow.

However, that does not have to be done with Ruby On Rails, not even with Ruby. It could well be in PHP using a similar framework or not. As a matter of fact many PHP frameworks appeared afterwards copying some things from Ruby On Rails.

Ironically certain things from Ruby On Rails were copied from PHP. For instance the ERB is a templating system that later merged in Ruby On Rails project. It is basically a way to define templates with some code inside, just like what you can do in PHP since ever.

It is even more ironic that some people preach that you should not mix code in HTML templates, as if that is an ugly thing and if do that you will go to hell when you die. After all, I guess Ruby On Rails people agree that programming does not have to be beautiful.

Another thing considered ugly by some is the use of global code in your applications instead of classes. Well, if you take a look at Wordpress source code, you see global code all over it.

I already have written about why organizing your code in classes is better than using global code but that does not have to be a mandatory rule for everything.

Global code may not be beautiful but it works, PHP allows it, a lot of developers use it, and make a living from it.

  5. PHP Detractors Have the Wrong Focus

PHP is not perfect but that does not matter. Actually those are not my words. Those are from Jeff Atwood of StackOverflow fame. Despite he knows that, it is not unusual to see him preaching against PHP. Well if it does not matter, why bother spending time and effort preaching against PHP?

Jeff is not alone. Haters will gonna hate, will do it in public spaces a lot, sometimes in disguised ways.

One site where I see a lot of disguised anti-PHP preaching is in Quora. This is a more sophisticated form of anti-PHP warfare. Some people make allegations against PHP disguised of questions. Some ask if PHP project startups have less chance of succeeding, others ask if PHP popularity is declining, others ask if PHP is still worth learning, and so on.

All this anti-PHP preaching is pointless. It only helps bringing more attention to PHP. Well, if other languages are so much better than PHP, why don't PHP haters try to be positive and focus their efforts in showing the benefits of other languages? That would probably be a better approach to attract more people to their language of choice.

Are you willing to move your PHP applications to Google AppEngine or do you feel it is not yet ready?

Ref: http://www.phpclasses.org/blog/post/208-5-Reasons-Why-the-Web-Platform-War-is-Over-PHP-Won-with-75-says-Google.html

Friday, May 17, 2013

How to enable cURL in server from terminal (ubuntu)

To enable curl package php5-curl should be installed. Open "Terminal" and execute the following command:
    sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

After installing libcurl you should restart the web server with following command,
sudo /etc/init.d/apache2 restart

Hope this solution will help to enable curl in your ubuntu system. It worked on mine :)

Thursday, May 16, 2013

Way to Access PhpMyAdmin when codeigniter is installed in the server

Codeigniter will block access to phpMyAdmin installed on subdirectory.
www.mysite.com <-- this to access CodeIgniterCMS based website
www.mysite.com/phpMyAdmin <-- this to access phpmyadmin installation, which currently inaccessible and just showing CI's default 404 error page
What should you do to able to access phpMyAdmin?
Answer is pretty simple. Your htaccess is not poking a hole through to let access to phpMyAdmin. Fix the htaccess like below
   RewriteEngine on
   RewriteCond $1 !^(phpMyAdmin|index\.php|robots\.txt)
   RewriteRule ^(.*)$ index.php?/$1 [L]

Then you are good to go.

Wednesday, May 15, 2013

Create Jquery Ajax with the Codeigniter Pagination Library Video Tutorial

In this screencast you are going to learn how to combine Jquery Ajax with the Codeigniter Pagination Library.

Note: I have wrote an article last week with complete source code on "How to implement jQuery Ajax with Codeigniter pagination library together with bootstrap styling". Click the following link to view the article.
How to use Codeigniter pagination library together with jQuery and AJAX with complete sourcecode?

 Ref: http://blip.tv/web-lee/codeigniter-pagination-part-4-2245514

Tuesday, May 14, 2013

Get File Name Without File Extension in PHP

Definition and Usage - basename()
The basename() function returns the filename from a path.

pathRequired. Specifies the path to check
suffixOptional. Specifies a file extension. If the filename has this file extension, the file extension will not show

$path = "/testweb/home.php";

//Show filename with file extension
echo basename($path) ."<br/>";

//Show filename without file extension
echo basename($path,".php");
The output of the code above will be:

You have to know the extension to remove it in advance though.

You can use pathinfo() and basename() together if you don't know the extension of the file.

First get the extension using pathinfo(), and use the basename function, like this:

$path = "/testweb/home.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

$file = basename($path, ".".$ext); // $file is set to "home"
Definition and Usage - pathinfo()

pathinfo() returns information about path: either an associative array or a string, depending on options.


1. If the path has more than one an extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one.
2. If the path does not have an extension, no extension element will be returned.

Ref: http://www.w3schools.com/php/func_filesystem_basename.asp and http://de.php.net/manual/en/function.pathinfo.php

Monday, May 13, 2013

Solution To Output a UTF-8 CSV in PHP That Excel Will Read Properly

Excel doesn't support UTF-8. You have to encode your UTF-8 text into UCS-2LE. It is very simple to change the encoding in PHP. You can use following PHP inbuilt function to covert encoding from utf8 to ucs-2le.

mb_convert_encoding($output, 'UCS-2LE', 'UTF-8');

Open the CSV with excel, it will display the special characters properly. It saved a lot of time for me at-least.

Let me know if it helped for you guys as well?

How to get the first word of a string/sentence in PHP?

There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of Test me more can be obtained by tokenizing the string on the space character.
$value = "Test me more";
echo strtok($value, " "); // Test
For more details and examples, see the strtok PHP manual page.

Alternative solutions

$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true); // will print Test
echo current(explode(' ',$myvalue)); // will print Test
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
$string = ' Test me more ';
preg_match('/\b\w+\b/i', $string, $result); 
echo $result; // will print Test

/* You could use [a-zA-Z]+ instead of \w+ if wanted only alphabetical chars. */
$string = ' Test me more ';
preg_match('/\b[a-zA-Z]+\b/i', $string, $result); 
echo $result; // will print Test
Ref: http://stackoverflow.com/questions/2476789/how-to-get-the-first-word-of-a-sentence-in-php

Wednesday, May 8, 2013

Exclude a certain row from an MYSQL query

You can exclude a certain row from sql query using '<>' or '!=' clause.

For example,  if you want to exclude the row in the result with user_id => 1 from the table 'poll', following query will give you the desired result.

SELECT *  FROM `poll` WHERE  user_id <> 1

If the data type of id is String you must use 
SELECT *  FROM `poll ` WHERE  user_id <> '1'

Note: In MySQL, you can also use != rather than <> but <> is ANSI and more portable.

Monday, May 6, 2013

CSS tricks to show or hide horizontal and vertical scroll bar

Sometimes we need to add scroll bar to a div or span whenever text in the div or span get overflow. scroll bar is supported in all browsers like IE 5+, FF 3.5+, and Safari, Opera etc. To show scroll bar, we need to specify overflow property of css to "visible" or "auto".

Horizontal and Vertical Scroll Bar
   overflow: auto; /*for horizontal and vertical scroll bars */

Horizontal Scroll Bar
       overflow-x: auto; /*for horizontal scroll bar */
       overflow-y: hidden; /*for hiding vertical scroll bar */

Vertical Scroll Bar
   overflow-x: hidden; /*for hiding horizontal scroll bar*/
   overflow-y: auto; /*for vertical scroll bar*/

Important to remember:
1. To show scroll bar always set overflow to "visible". It will show scroll bar whether text get overflow or not.
2. To show scroll bar only, when text get overflowed, set overflow property to "auto".

Ref: http://www.dotnet-tricks.com/Tutorial/css/G348190612-CSS-to-show-only-horizontal-and-vertical-scroll-bar-in-div.html

Thursday, May 2, 2013

Using jQuery To Filter Data

Fig: Screenshot of the result

When a webpage is designed to display large tables of data, a great amount of consideration should be dedicated to allowing the user to sort through the data in a structured manner. In this article, I will go over one techniques:  filtering.

If a website calls for many records of data to be displayed, in my example 1000 rows, then it
is more than appropriate to offer the user a way to sift through the data. One particularly effective way that has sprung up on the web in recent years as part of
the Web2.0/AJAX movement is filtering. This is also something that Apple pushes heavily in there applications such as iTunes. The goal for us is to allow the user
to type a search query into a standard text input and live filter the table rows below only showing the ones that contain matching text. This is arguably more
advanced then the alternating row styles, but in all reality requires minimal code, due to jQuery’s built-in functionality.
First we will write a generic function that takes a selector and a string of text. This function will then search all elements matching that selector looking for
the string. If it finds the string, it will show the element and apply a class name of visible to the element, otherwise it hide the element. Why are we applying
the class of visible? Well once the items are sorted we will want to run the zebraRows function again, but we need to tell jQuery to ignore the hidden rows, and
the best way I have found to do that is apply a class of visible.
The actual searching is done by the JavaScript function, aptly named, search(). Though due to the way the DOM works, if we don’t employ the jQuery function,
text(), the box will also look at any HTML tags that happen to be in the table row, such as <td>. We
will employ a little more functionality by not just searching for the exact string the user has typed, but rather if any of the words in the query are in a row.
This is ideal because it allows for “lazy searching”, the user isn’t required to remember an exact string but rather just parts of it. The search() function takes
a regular expression as its parameter, and so we must strip all white space from the beginning and end of our query and put “|” characters in between each word to
achieve the OR functionality we desire.
  1. //filter results based on query  
  2. function filter(selector, query) {  
  3.   query =   $.trim(query); //trim white space  
  4.   query = query.replace(/ /gi, '|'); //add OR for regex query  
  6.   $(selector).each(function() {  
  7.     ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');  
  8.   });  
  9. }  

The sixth line is where the magic happens, and probably requires a bit of explanation. Starting at line 5, we are telling the code to loop through all the elements
that match the selector, i.e. the rows, and then we want to execute the code on line 6 using each one. Line 6 is a bit complicated if you are new to programming,
but it is fairly easy to grasp if we split it up. Think of everything before the question mark as being a question, if the answer to that question is true then
execute the code to the left of the colon, but after the question mark. If the answer is false then execute the code after the colon. This is essentially an if
statement but in a more concise form known as a ternary operator, and would be no different than writing:

  1. ...  
  2.   if ($(this).text().search(new RegExp(query, "i")) < 0) {  
  3.     $(this).hide().removeClass('visible')  
  4.   } else {  
  5.    $(this).show().addClass('visible');   
  6.   }  
  7. ...  
The reason we ask if search() returns "< 0" is because it returns the position in the string where query is, and -1 if nothing is matched. Because -1 is always
less than zero, we test that condition. In theory there is nothing wrong with checking if it returns (==) -1, but it in practice it is safer to just assure it is
less than zero.
Alright now that we have a complete filter function, let's use jQuery events to hook it up to the input. To achieve the live effect we desire the event we want to
watch for is when user releases a key while they are focused on the text box, known as keyup in JavaScript. It is important that we set the ID attribute of the
input so we can target it using jQuery. Back in our ready function we need to add code after our call to zebraRows().
  1. <label for="filter">Filter</label>  
  2. <input type="text" name="filter" value="" id="filter" />  
And the jQuery code:
  1. ...  
  2.   //default each row to visible  
  3.   $('tbody tr').addClass('visible');  
  5.   $('#filter').keyup(function(event) {  
  6.     //if esc is pressed or nothing is entered  
  7.     if (event.keyCode == 27 || $(this).val() == '') {  
  8.       //if esc is pressed we want to clear the value of search box  
  9.       $(this).val('');  
  11.       //we want each row to be visible because if nothing  
  12.       //is entered then all rows are matched.  
  13.       $('tbody tr').removeClass('visible').show().addClass('visible');  
  14.     }  
  16.     //if there is text, lets filter  
  17.     else {  
  18.       filter('tbody tr', $(this).val());  
  19.     }