Monday, August 5, 2013

How to set chmod for a folder and all of its subfolders and files in Linux Ubuntu Terminal?

to change all the directories to 755:
    find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
to change all the files to 644:
    find /opt/lampp/htdocs -type f -exec chmod 644 {} \;

Friday, January 4, 2013

PHP explode function

PHP explode function

The explode function is used to split a string by a specified string into pieces i.e. it breaks a string into an array.

The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

for more details please visit http://php.net/manual/en/function.explode.php

array explode ( string $delimiter , string $string [, int $limit ] )

explode function request 3 parameters, but the last one is optional. Let see what are these parameters.

$delimiter - to break a string into smaller text with each break occurring at the same symbol, this would be the symbol
$string - String that you want to split
$limit - Limit is optional param but would may be tricky. You must concern following points when you are try to use limit.
  • If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
  • If the limit parameter is negative, all components except the last -limit are returned.
  • If the limit parameter is zero, then this is treated as 1.
Let see some example codes:

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));


Above code will output the following:
Array
(
    [0] => one
    [1] => two|three|four
)

<?php
$str = 'one|two|three|four';

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));


Above code will output the following:
Array
(
    [0] => one
    [1] => two
    [2] => three
)


<?php
$str = 'one|two|three|four';

// limit with 0 and 1 would be same
print_r(explode('|', $str, 0));



Above code will output the following:

Array
(
    [0] => one|two|three|four
)

PHP implode function

implode() Function

The implode function is used to join an elements of an array with a string.

The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.

Let's take an example:

If you want to separate array values with a dashed (-), Following statement is just fine.

<?php

$array = array('XXX', 'TTT', '2123123');
$dash_separated = implode("-", $array);

var_dump($dash_separated);

It will output the result as follows :

string(15) "XXX-TTT-2123123"

Here are the tricky ways of implode will get naughty.

1) When try to implode with empty array.
eg:

<?php
//When using empty array it will return empty string even passed the glue 
var_dump(implode('hello', array()));


Above code will output empty string as :


string(0) ""


2) When try to implode with array with boolean.

eg:
<?php

//When imploding boolean values it will just return the values of true
var_dump(implode('',array(true, true, false, false, true)));



Above code will output only true(s) as :

string(3) "111"

Advanced usage of implode method

If you are dealing with sql functions the implode method is just perfect. try following codes:

<?php

//Quite handier with sql functions with arrays

$fields = array(
        'subject' => 'go green',
        'message' => 'i am going to take off!'
);

$sql = 'INSERT INTO table_name';
$sql .= " VALUES (`" . implode("`,`", array_keys($fields)) . "`)";
$sql .= " ('" . implode("','", $fields) . "')";

var_dump($sql);

$userIds = array(2, 32, 55, 200, 44);

$sql2 = "SELECT * FROM table_name";
$sql2 .= " WHERE 1 AND (id=" . implode(" OR id = ", $userIds) . ")";

var_dump($sql2);



Above codes will give the output as follows:


string(90) "INSERT INTO table_name VALUES (`subject`,`message`) ('go green','i am going to take off!')"
string(88) "SELECT * FROM table_name WHERE 1 AND (id=2 OR id = 32 OR id = 55 OR id = 200 OR id = 44)"

Happy coding ~

Thursday, September 13, 2012

Transactions in MySQL


Definition of a transaction

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

MySQL supports several storage engines. The InnoDB is fully ACID compliant. The ACID stands for Atomicity, Consistency, Isolation and Durability. Reliable transactions must support all these four properties.

Operations within a transaction must be atomic. This means, that either all operations succeed or fail. This is all or nothing rule. The consistency property ensures that the database is in a consistent state after the transaction is finished. The data is valid and there are no half-finished records. For example there are no customers left with no payment records or there are no payment records without customers. Isolation is the requirement that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions. Without isolation, the data may end up in inconsistent state. Durability is the ability of the database system to recover the committed transaction updates against any kind of system failure.

The default transaction isolation level for MySQL is repeatable read.

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+

The current isolation level is stored in the tx_isolation server variable.

mysql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

mysql> SELECT @@tx_isolation;
+----------------+
| @@tx_isolation |
+----------------+
| SERIALIZABLE   |
+----------------+

We can change the isolation level with the SET TRANSACTION ISOLATION LEVEL statement.


Autocommit


MySQL also automatically commits statements that are not part of a transaction. The results of any UPDATE or INSERT statement not preceded with a START will immediately be visible to all connections.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

The autocommit variable is set by default.

mysql> SET autocommit=0;

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+

The autocommit can be turned off.
Now we are going to demonstrate the autocommint variable.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

CREATE TABLE Test(Num INTEGER NOT NULL) engine=InnoDB;

The autocommit is set. We create a simple Test table with InnoDB storage engine, which supports transactions.

mysql> INSERT INTO Test VALUES (1), (2), (3);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

We insert three rows into the column of the table. The values are immediately committed.

mysql> SET autocommit=0;

mysql> INSERT INTO Test VALUES (4), (5);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we set the autocommit variable to false. We insert two values and select all data from the table. We have now 5 rows in the table.

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

However, the data is not permanently written to the table. With the ROLLBACK statement, we take them back.

mysql> INSERT INTO Test VALUES (4), (5);

mysql> COMMIT;

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we insert value 4, 5 again. This time, the rows are committed with the COMMIT statement. Subsequent rollback statement has no effect.


Starting transactions

With autocommit enabled, each single SQL statement is wrapped automatically in its own transaction. To start our own transaction, we issue the START TRANSACTION statement. The transaction is later finished with the COMMIT or ROLLBACK statements. Multiple statements may be issued in the body of the transaction. All are either committed or rolled back as one unit.

mysql> TRUNCATE Test;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT * FROM Test;
Empty set (0.00 sec)

We will work with the same Test table. We truncate the data in the table.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (1), (2);

mysql> INSERT INTO Test VALUES (3), (4);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+

In the above code, we start a transaction and insert four rows into the table. The values are not yet committed. From the current connection the rows are visible.

$ mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 65
Server version: 5.1.41-3ubuntu12.9 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT * FROM mydb.Test;
Empty set (0.00 sec)


However, from a different connection, the Test table is empty. We launch a new instance of a mysql client program. This is a different connection to the MySQL database. From this connection, the values are not yet visible.


mysql> COMMIT;

Finally, the COMMIT statement commits the data to the table. The rows are visible from both connections.

We start another transaction. This time the data will be rolled back.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (5), (6);

mysql> INSERT INTO Test VALUES (7), (8);

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+



In the above SQL code, we start a new transaction. We insert four values into the Test table. We roll the changes back with the ROLLBACK statement. Subsequent select from the table shows that the data was not committed to the table.

Tuesday, August 28, 2012

How to find a content of a file linux

You can find content inside a file by using Linux grep command. eg : If you want to find the usage of text called "Hello". You can type as follows:

grep -r hello .

-r option means read all files under each directory, recursively
hello - means the content what you want to search
. - means the path for this scenario it means from current folder.(You can use absolute path as well eg: /home/gayan/)

Enjoy ~

Wednesday, August 1, 2012

Database Access Object Pattern using PHP


The simplest web widget to the most complex online e-commerce website have one thing in
common: they deal with data. So much of programming revolves around data access and
manipulation. With the massive proliferation of the Internet, cheaper storage devices, improved understanding of analytics, and greater expectations for information access, data is being leveraged in more interesting and unique ways. The Data Access Object Design Pattern aims to help construct objects that can work easily (transparently) with all of this data.

Programming typically can be a lot of repetition. This was especially true before more popular frameworks started being released. Most PHP programmers can count into the double digits the number of CRUD (create, read, update, delete) applications they’ve had to make. One of the major portions of repetition in the standard create/update application is the data source manipulation. For the rest of the discussion, I’m going to stop generalizing the data source and refer to it as SQL.

In the application, a SQL statement has to be written to create the entity in the database. Next, an additional SQL statement must be written in order to provide updates to any of the individual features of that entity. The repetition involved in creating these SQL statements is not only boring but also not best practice.

Code example

First create your own database and create following table

 CREATE TABLE task (  
      id INT PRIMARY KEY AUTO_INCREMENT,  
      subject VARCHAR(255),  
      description text  
 );  

Create php file called "baseDao" and put following code

 <?php  
 class baseDao  
 {  
   private $connection;  
   public function __construct() {  
     $this->connectToDb(DB_USER, DB_PASS, DB_HOST, DB_NAME);  
   }  
   public function connectToDb($user, $pass, $host, $database) {  
     $this->connection = mysql_connect($host, $user, $pass);  
     mysql_select_db($database, $this->connection);  
   }  
   public function fetch($value, $key = NULL)  
   {  
     if (is_null($key)) {  
       $key = $this->_primaryKey;  
     }  
     $sql = "SELECT * FROM {$this->_tableName} WHERE {$key} = '" . $value . "';";  
     $results = mysql_query($sql, $this->connection);  
     $rows = array();  
     while ($result = mysql_fetch_array($results)) {  
       $rows[] = $result;  
     }  
     return $rows;  
   }  
   public function update($keyedArray)  
   {  
     $sql = "UPDATE {$this->_tableName} SET ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates[] = "{$column}='" . $value . "'" ;  
     }  
     $sql .= implode(",", $updates);  
     $sql .= " where {$this->_primaryKey}='". $keyedArray[$this->_primaryKey] . "';";  
     mysql_query($sql, $this->connection);  
   }  
      public function save($keyedArray)  
   {  
     $sql = "INSERT INTO {$this->_tableName} ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates_columns[] = "{$column}";  
       $updates_values[] = "'" . $value . "'" ;  
     }  
           $sql .= "(";  
     $sql .= implode(",", $updates_columns);  
           $sql .= ")";  
           $sql .= " VALUES (";  
     $sql .= implode(",", $updates_values);  
     $sql .= ");";  
     if (!mysql_query($sql, $this->connection))  
                echo mysql_error();  
   }  
 }  

Finally you can use the dao class as follows:


 <?php  
 //DB_USER, DB_PASS, DB_HOST, DB_NAME  
 define('DB_USER', 'root');  
 define('DB_PASS', '');  
 define('DB_HOST', 'localhost');  
 define('DB_NAME', 'blog_samples');  
 //include "baseDao.php";  
 include "taskDao.php";  
 $taskDao = new taskDao();  
 $updates=array('subject' => 'testSubjectValue', 'description' => 'testDescriptionValue');  
 $taskDao->save($updates);  
 echo "<br/>Dao pattern !<br/>";  
Good luck !

Friday, July 27, 2012

Builder design pattern using php

Software complexity is an interesting thing. The requirements for software are complex as are the functionality of a software package or product. Even the code that makes up the software is complex. The focus of the Design Pattern approach is to provide maintainability, architectural 
strength and reduced complexity. With the host of complex objects making up most software repositories, solutions involving the Builder Design Pattern have their work cut out for them.

Code example

The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.

class Product
{
    protected $type = '';
    protected $size = '';
    protected $color = '';
    protected $price = '';

    public function setColor($color)
    {
        $this->color = $color;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setType($type)
    {
        $this->type = $type;
    }


    public function setPrice($price)
    {
        $this->price = $price;
    }

    function __toString()
    {
        $text = 'Product { ';
        $text .= ":type => " . $this->type;
        $text .= ", :size => " . $this->size;
        $text .= ", :color => " . $this->color;
        $text .= ", :price => " . $this->price;
        $text .= " }";
        return $text;
    }

}


To create a complete product object, the product configurations need to be passed individually to each of
the methods of the product class:


// our product configuration received from other functionality
$productConfigs = array(‘type’=>’shirt’, ‘size’=>’XL’, ‘color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);


Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.


The productBuilder class is designed to accept those configuration options that are required to build
the product object. It stores both the configuration parameter and a new product instance on
instantiation. The build() method is responsible for calling each of the methods in the product class to
fully complete the product object. Finally, the getProduct() method returns the completely built
product object.




class ProductBuilder
{

    protected $product = NULL;
    protected $config = array();

    public function __construct($config){
        $this->product = new Product();
        $this->config = $config;
    }

    public function build() {
        $this->product->setType($this->config['type']);
        $this->product->setColor($this->config['color']);
        $this->product->setSize($this->config['size']);
        $this->product->setPrice($this->config['price']);
    }

    public function getProduct() {
        return $this->product;
    }
}

Note that this build() method hides the actual method calls from the code requesting the new product. If the product class changes in the future, only the build() method of the productBuilder class needs to change. This code demonstrates the creation of the product object, using the productBuilder class:


$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

The Builder Design Pattern is meant to eliminate the complex creation of other objects. Using the Builder Design Pattern is not only best practice but it also reduces the chances of having to repeatedly alter pieces of code if an object’s construction and configuration methods change.