Sabtu, 28 Juni 2014

How to create chaining in PHP

Most of new programmers using the chain method in their code. Actually they just follow the tutorial on the book.

If you are new programmer, you need to read this simple post for better understanding.

After reading this post, I hope you know how chaining works and how to make chaining.

Let start from a case; I use a query case like this;
select id, country_name from country_table order by id desc

Let solve that case.
First, you need to create 'a chaining class';

class MySimpleQuery 
    static public function myQuery()
        return new self();
    public function select($field)
        echo "select $field ";
        return $this;

    public function table($table)
        echo "from $table ";
        return $this;
    public function order($field,$direction) 
        echo "order by $field $direction ";
        return $this;

Now you want to call it right? This is how to call it;

$my_query = MySimpleQuery::myQuery()
        ->select('id, country_name')

If you echoing $my_query, you will see;
select id, country_name from country_table order by id desc

Well, that's it. You can develop above sample towards. 

Selasa, 24 Juni 2014

The most effective way to store user activity

Today, I made a company website. The website owner asked me to store all of user activities. 
This challenge is quite interesting. The normal way is storing the data right in the table in question. But, I think the best way is storing the data into is just using one table.

All we have to do is create a table to store it with json format.

You can use array and then encode it into json format.
I use a PHP code to explain;
//activity data
$user_id = $_SESSION['user_id'];
$activity = "INSERT";
$table = "posts";
$data = array(
    'id' => $id,
    'post_date' => $post_date,
    'post_content' => $post_content
$the_data = json_encode($data);
mysql_query("insert into user_activity_table (user_id, activity, table, data) values ('$user_id', '$activity','$table','$the_data')");

This is an example of user_activity_table
| ID | user_id | activity | table  | data                 |
| 1  | 1       | INSERT   | posts  |{ "id": "2", [...] }  |
| 2  | 3       | UPDATE   | photos |{ "id": "5", [...] }  |

We can take a lot of advantage of using json format. Among the advantages is we can recover deleted data.

In the end I say, you can elaborate the method according to your needs. :)

Sabtu, 21 Juni 2014

An effective way to pass the data into the view in Laravel

To make it easier to digest this post, I use a pagination case.

Normally, you will have this variable request for pagination;
$page = Input::get('page'); 
$perpage = Input::get('perpage'); 
$sidx = Input::get('sidx');   //order field
$sord = Input::get('sord'); //order direction

Next thing you want to do is passing the data into view, right?
And in normal way, most of coder write code like below;
return View::make('page_search')

And retrieving the data like this
<input type="hidden" name="page" value="{{ $page }}" >
<input type="hidden" name="perpage" value="{{ $perpage }}" >
<input type="hidden" name="sidx" value="{{ $sidx }}" >
<input type="hidden" name="sord" value="{{ $sord }}" >

All above code look like this;
public static function getSearch()
    $page = Input::get('page'); 
    $perpage = Input::get('perpage'); 
    $sidx = Input::get('sidx');   //order field
    $sord = Input::get('sord'); //order direction

    $search_data = "your eloquent query here related to your page, perpage, sidx, sord";

    //passing the data into view
    return View::make('page_search')
        ->with('search_data', $search_data)

{{ Form::open(.......) }}
<input type="hidden" name="page" value="{{ $page }}" >

<input type="hidden" name="perpage" value="{{ $perpage }}" >
<input type="hidden" name="sidx" value="{{ $sidx }}" >
<input type="hidden" name="sord" value="{{ $sord }}" >
<input type="submit" value="Search">
{{ Form::close() }}

Well, nothing wrong with above code. But you can do better with this;
public static function getSearch()
    $page = Input::get('page'); 
    $perpage = Input::get('perpage'); 
    $sidx = Input::get('sidx');   //order field
    $sord = Input::get('sord'); //order direction

    $search_data = "your eloquent query here related to your page, perpage, sidx, sord";

    $form['page'] = $page;
    $form['perpage'] = $perpage;
    $form['sidx'] = $sidx;
    $form['sord'] = $sord;

    /* OR LIKE THIS */
    $form = array('page' => $page, 'perpage' => $perpage, 'sidx' => $sidx, 'sord' => $sord);

    //passing the data into view
    return View::make('page_search')
        ->with('search_data', $search_data)

{{ Form::open(.......) }}
<input type="hidden" name="page" value="{{ $form['page'] }}" >

<input type="hidden" name="perpage" value="{{ $form['perpage'] }}" >
<input type="hidden" name="sidx" value="{{ $form['sidx'] }}" >
<input type="hidden" name="sord" value="{{ $form['sord'] }}" >
<input type="submit" value="Search">
{{ Form::close() }}

As you can see above, you can use an array for your data. :)

Selasa, 17 Juni 2014

Getting an Image of The HTML Article with PHP preg_match Function

This case occurs in many blog.

You want to show a brief description of an article along with the image which is contain in it article.

You can see what I mean as shown below;

In that case, you don't need to create a new field contain an image in it. You just need to parse the img tag.
This is the code:

private static function getImageInPost($post_content)
    $jum = preg_match_all('/src="([^"]*)"/', $post_content,$matches);
        foreach ($matches as $match) 
            if(strpos($match[0], "src")!== false)
                $res = explode("\"", $match[0]);
                $image = "<img src='".$res[1]."'>";
        $image = "";
    return $image;

Above code returning first image in the article.

Jumat, 13 Juni 2014

Updating Ubuntu 12.04 Server via Terminal

Sometimes, when you logged in into your server, you have found like the picture below.

Ubuntu tells you that you have 20 packages can be updated and 20 updates are security updates.
It's easy when you have a graphical user interface. You can go to your 'update manager GUI' and just press update.

Well... in this post, I will show you how to upgrading Ubuntu via Terminal

First, you must updating your repository;
sudo apt-get update

And upgrading with this command;
sudo apt-get dist-upgrade

That's it. Easy, right...

Selasa, 10 Juni 2014

The Tools You Need as A Web Developer

As a web developer, you need these tools;

This tool gives you the speed of the website and how the optimization

As you can see the picture bellow, you know what page test is

3. Google Analytics
This tool is used to analyze the traffic of your website such as, keywords, visitors, demographics etc

4. Google Webmasters

5. CSS Minifier

My Workbench Setting

This post may not be directly related to Information Technology (IT).

Today I am lazy to write code. I was idly and I took my workbench photo. Hehe... The picture resolution is not good enough, my table messed up and there is my lunch on it. Yeah, I cooked it.

I enjoy the workbench arrangement; monitor at top and laptop screen at bottom. Once I arrange the monitor at right side or left side and it makes my neck hurt when looking at left or right. So, this is my best arrangement for monitor and laptop.

In this arrangement, I can easily writing code tilt down and when I want to see the result, I tilt up.

And What is your best arrangement?

Flushing DNS Cache on Ubuntu 12.04

Honestly, I often facing this problem especially when managing and configuring my server.

In this tutorial, make sure nscd installed on your machine first. If it doesn't, the command will not working. In otherword, you can't flushing your DNS through this way.

sudo apt-get install nscd

sudo /etc/init.d/nscd status

sudo /etc/init.d/nscd start

sudo /etc/init.d/nscd stop

sudo /etc/init.d/nscd restart

#Flushing DNS
sudo /etc/init.d/networking restart

#Cleaning DNS and start
sudo /etc/init.d/dns-clean start

This is the screen shot:

Senin, 09 Juni 2014

Taking Advantage of Using PHP Class in Netbeans

I have done many things in my favorite IDE; Netbeans.

I have done java code, javascript code, HTML code and PHP code with it.

For now, I want to tell you how I take an advantage of using Netbeans and PHP class.
Here, I give you an example and showing an advantage of using Netbeans

Class Something {

    * @param string $title
    public static function getFixedNav($title)
        <div id="fixed_nav"><?= $title; ?></div>

From above class, when you need to call it, you can type Something::getFix and Netbeans autocompleted it into like this figure below

jQuery Chaining

Well, this is simple post.

I just want to tell you about chaining jquery.

This is essential method to code with jquery. Most of beginner code look like this;


I think above code is bad practice. When you are dealing with tons of code, It look like mess.

The best code should look like this (chaining);


Minggu, 08 Juni 2014

Users Logging in into The Application Automatically

In some case, you don't want the user to type something to login.

In my case, I send an email to the user. The user clicked a link in their email and the user automatically logged in into the application.

I am sure you have a lot of reason for logging in the user without typing anything.

In Laravel documentation, they named it Manually Logging In Users. Well, I named it Automatically Logging In Users. Hehe... You choose whatever name is suitable for you.

This is the snippet;

//find the user id
$user = User::find(1);

//You can logging in the user 

Or the other way, you can logging in your user by a key that your have made in your database.

//Find the user base on a key
$user = DB::table('users')->where('the_key','=',$key)->first();
//automatically logging in

Javascript Key Codes

Honestly, I can't remember and I don't want to memorize all of these keycode.

I think I must write this code into my blog.

This is the keycode:

Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
Key Code
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
Key Code
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

Sabtu, 07 Juni 2014

Step by Step How to Add Facebook Like Button to Your Web Page

Facebook gives you 4 alternative methods; HTML5, XFBML IFRAME and URL to add like button to your page.

But in this step by step tutorial I am gonna show you to add to your page with HTML5 method.

Step 1. Placing element root to your page

<div id="fb-root"></div>

Step 2. Placing Javascript Facebook SDK right after the root element

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); = id;
  js.src = "//";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Step 3. Adding like button to wherever you want to 'this' page.

<div class="fb-like" data-href="" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>

Final code should look like this

        <title>your web title</title>
        <div id="fb-root"></div>
        <script>(function(d, s, id) {
          var js, fjs = d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) return;
          js = d.createElement(s); = id;
          js.src = "//";
          fjs.parentNode.insertBefore(js, fjs);
          }(document, 'script', 'facebook-jssdk'));</script>
        <div>YOUR HEADER</div>
        <div>YOUR CONTENT</div>

        <!-- the like button -->
            <div class="fb-like" data-href="" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>

Step by Step Installing Nodejs on Ubuntu

This is step by step installing nodejs on Ubuntu

1. Installing python
sudo apt-get install python-software-properties python g++ make

2. Adding repository

sudo add-apt-repository ppa:chris-lea/node.js

3. Update

sudo apt-get update

4. Installing nodejs

sudo apt-get install nodejs

Jumat, 06 Juni 2014

Creating a PDF file using FPDF

In this post, I will show you how create pdf using FPDF plugin.

First, you must have a fpdf, in this case I have downloaded fpdf17.php and including it into my code. For sure, you can see this example to create your own PDF file.


include "libConnect.php";

class PDF extends FPDF {

    var $B;
    var $I;
    var $U;
    var $HREF;

    function PDF($orientation = 'P', $unit = 'mm', $size = 'A4') {
    // Call parent constructor
    $this->FPDF($orientation, $unit, $size);
    // Initialization
    $this->B = 0;
    $this->I = 0;
    $this->U = 0;
    $this->HREF = '';

    function WriteHTML($html) {
    // HTML parser
    $html = str_replace("\n", ' ', $html);
    $a = preg_split('/<(.*)>/U', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
    foreach ($a as $i => $e) {
        if ($i % 2 == 0) {
        // Text
        if ($this->HREF)
            $this->PutLink($this->HREF, $e);
            $this->Write(5, $e);
        else {
        // Tag
        if ($e[0] == '/')
            $this->CloseTag(strtoupper(substr($e, 1)));
        else {
            // Extract attributes
            $a2 = explode(' ', $e);
            $tag = strtoupper(array_shift($a2));
            $attr = array();
            foreach ($a2 as $v) {
            if (preg_match('/([^=]*)=["\']?([^"\']*)/', $v, $a3))
                $attr[strtoupper($a3[1])] = $a3[2];
            $this->OpenTag($tag, $attr);

    function OpenTag($tag, $attr) {
    // Opening tag
    if ($tag == 'B' || $tag == 'I' || $tag == 'U')
        $this->SetStyle($tag, true);
    if ($tag == 'A')
        $this->HREF = $attr['HREF'];
    if ($tag == 'BR')

    function CloseTag($tag) {
    // Closing tag
    if ($tag == 'B' || $tag == 'I' || $tag == 'U')
        $this->SetStyle($tag, false);
    if ($tag == 'A')
        $this->HREF = '';

    function SetStyle($tag, $enable) {
    // Modify style and select corresponding font
    $this->$tag += ($enable ? 1 : -1);
    $style = '';
    foreach (array('B', 'I', 'U') as $s) {
        if ($this->$s > 0)
        $style .= $s;
    $this->SetFont('', $style);

    function PutLink($URL, $txt) {
    // Put a hyperlink
    $this->SetTextColor(0, 0, 255);
    $this->SetStyle('U', true);
    $this->Write(5, $txt, $URL);
    $this->SetStyle('U', false);


$pdf = new PDF();

// First page
$pdf->WriteHTML("<b>Detail Pelabuhan ".$data['nama_pelabuhan']."</b>");
$pdf->Write(5,"Provinsi: ".$data['nm_prov']);
$pdf->Write(5,"Kabupaten/Kota: ".$data['nm_kabkota']);
$pdf->Write(5,"Koordinat Geografis: ".$data['latitude'].", ".$data['longitude']);



    $pdf->WriteHTML("<b>Informasi Umum</b>");

    $ihigh = 7;

    // row 1

    //row 2

    //row 3

    //row 4
    $pdf->Cell(30,$ihigh,$data['kedalaman_alur']." m",T,1,'R');

    //row 5
    $pdf->Cell(30,$ihigh,$data['kedalaman_kolam']." m",T,1,'R',true);

    //row 6
    $pdf->Cell(30,$ihigh,$data['kap_tot']." ton",TB,1,'R');


FPDF Website: And you can find another script here:

PHP Connection Snippet

I often forget about this, I bet you often forget about this too. Yeah, this only happens once in programming. Especially this happen when you write your application without a framework.

Here it the snippet, you can copy - paste into your code.

$my['host']    = "localhost";
$my['user']    = "root";
$my['pass']    = "password";
$my['dbs']    = "database_name";

$connect    = mysql_connect($my['host'], $my['user'], $my['pass']);
if (! $connect) {
  echo "Connection Fail..!";

     or die ("Can't find the database ".mysql_error());

Jquery Mobile Popup Window Snippet

This is code snippet for jquery mobile popup window

<a href="#popupDialog{{ $acc->ID }}" 

<!-- dialog -->
<div data-role="popup" 
    id="popupDialog{{ $acc->ID }}" 
        <div data-role="header" data-theme="a">
    <div data-role="content" data-theme="d">
        <p>This action cannot be undone.</p>
        <p>Are you sure want to delete {{ $acc->ID }}?</p>
        <a href="#" data-role="button" 
            data-inline="true" data-rel="back" data-theme="c">
        <a href="#" data-role="button" 
            data-rel="back" data-transition="flow" 
            data-theme="b" id="yesConfirm" 
            onclick="alert('test {{ $acc->ID }}');">
<!-- dialog -->

Kamis, 05 Juni 2014

Snippet for JQuery Ajax Post Method

This is how to do jquery ajax with post method;

Method 01;

    <input type="text" id="one" name="one">
    <input type="text" id="two" name="two">
    <div id="btnSubmit">Submit</div>
        var data = "one="+$("#one").val()+"&two="+$("#two").val();

Method 02;

<form id="nu_form">
    <input type="text" name="a_name" />
    <input type="text" name="something" />
 <input type="submit" value="save" id="btn_save" />
        data: $("#nu_form").serialize(), 
        type: 'POST',  
        url: '/save_data', 
        success: function(response) { 
            alert(response); } 
    return false; 

How to Install Run File

This is the snippet for installing dot run file.

In this case, I am using a file name can change it whatever your file name. Then you can follow this step;

1. Open a terminal. In Gnome the terminal is found in Applications>Accessories>Terminal.

2. Navigate to the directory of the .run file. For this example, I have mine on the desktop so I would type in "cd ~/Desktop" and press enter.

3. Type "chmod +x" (press enter).

4. Now type "./", press enter, and the installer will run.    

How to Create a Tooltip in EXTJS

This is the snippet for tooltip in EXTJS

    xtype: 'textfield',
    anchor: '100%',
    name: 'Alamat',
    fieldLabel: 'Alamat',
    emptyText: 'Alamat',
    listeners : {
       render: function(p) {
            var theElem = p.getEl();
            var theTip = Ext.create('Ext.tip.Tip', {
                html: 'Tuliskan nama jalan dan nomor rumah.<br>Misal: Jl. Merak, No. 3',
                margin: '0 0 0 200',
                shadow: false
            p.getEl().on('mouseover', function(){
                theTip.showAt(theElem.getX(), theElem.getY());
            p.getEl().on('mouseleave', function(){

Setting Up Virtual Hosts on Local Ubuntu

Create a virtual host on Ubuntu server is done in the following way;

1. Go to folder /etc/apache2/conf.d/ and create a new file. Example; mylaravel.conf

    DocumentRoot "/home/kenzominang/mylaravel/public" ServerName virtual_ok
    <Directory "/home/kenzominang/mylaravel/public">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all

2. Open /etc/hosts and add this line below mylaravel

3. Restart apache to make it work

$ sudo /etc/init.d/apache2 restart

How to Set up Session with Laravel

We usually play with session and create the session by server side script like PHP. But, how we create session with client side script?

In this case is EXTJS, you can store cookie instead of session.

The first thing you need to do is setProvider and set a variable into it;

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

And then to get varA from cookies;


And if you need to clear that value from cookies


That's it!

Renaming Every Single Tabel in MySQL Database to Lower Case on XAMPP Server

I actually use Ubuntu every day. But sometimes I perforce work with Windows, because my client familiar with Windows. In this case, my client is government. I had to teach an application that I made to the staff with Windows OS.

Well... That's just introduction that I sometimes work with XAMPP-Windows server.

In that case, I found trouble when importing MySQL database on XAMPP-Windows. Every single table name on it renaming to lower case. This situation made my application didn't work at all. And here's what I have done to rename every single table name (case sensitive);

  1. Find
  2. Look up for:
    # The MySQL server [mysqld]
  3. Add line
    lower_case_table_names = 2
    In some case that I have read, you must add that line at the end of file
  4. Save that file and restart your MySQL

Wildcard Sub Domain Setup in CPanel

Do you want to make a website like wordpress or blogspot with any subdomain on it?
This is very easy task if you try with CPanel & WHM 11. All you have to do is just type an asterix (*) symbol on sub-domain and every single sub domain you type on url, its gonna be your subdomain :)

Enabling PHP mod_rewrite Module

If you are frequently writing PHP script using a framework, I am pretty sure that you want a beautiful URL.

And for sure, you are using local server to test it. By default mod_rewrite is not enable on Apache server. To enable it, just write this on command line;

$ sudo a2enmod rewrite

After that, you have to restart Apache to make the configuration work

Start, Stop and Restart Apache Service

This command line is using Ubuntu and you must log in as super user;

Starting an Apache service;
$ sudo /etc/init.d/apache2 start

Stoping an Apache service;
$ sudo /etc/init.d/apache2 stop

Restarting an Apache service;
$ sudo /etc/init.d/apache2 restart

EXTJS Static Combobox

Sometimes you don't want to make a separate store and modal in your code. A lot of file make you hard to maintain your application. Especially the combobox and the store just shows once in your application. So, you just need a static combobox. Here it is the code;

Altirenative 1;
    fieldLabel:'Field Label',
    displayField:'Display Field',

Alternative 2:
// The data store containing the list of states
var pilihan = Ext.create('', {
    data :[

// Create the combo box, attached to the states data store
    store: pilihan, 

Alternative 3:
    anchor: '100%',
    store: Ext.create('', {
        fields: ['value', 'display'],
        data: [
                "display": "Ya",
                "value": 1
                "display": "Tidak",
                "value": 0
    valueField: 'value',

Get Last Inserted ID using Laravel Eloquent

This is the code

$theId = DB::getPdo()->lastInsertId();

Cara Mengetahui Besar Database PostgreSQL Tanpa Mendownloadnya

Berikut adalah langkah-langkah untuk mengetahui ukuran semua database di instance PostgreSQL yang berjalan di dalam kontainer Docker: 1. Men...