Friday, March 17, 2017

Copy text value to clipboard using jQuery

Its very important task for us to able to copy some value to clipboard using jQuery. Its now so much easy to make it without any hassle. Almost all browser support it. Its nothing but use some jQuery code to make it easier.


function copyTextToClipboard($value) {
    var $temp = $("<input>");
    $(document.body).append($temp);
    $temp.val($value).select();
    document.execCommand("copy");
    $temp.remove();
    alert("Text copied to your clipboard");
}

How to Paginate Data With PHP

Its sometime we found that we need a pagination but its difficult to make it as easy as we think. Below is a code snippet to make an standard pagination system using PHP code. Its nothing but you have to pass some arguments to make a better pagination system.

$paginator = new stdClass();
$paginator->total = 444;
$paginator->limit = 10;
$paginator->page = 1;
$paginator->links = 5;
$paginator->list_class = "pagination";
$paginator->link = "/users/list?q=value;
 
$html = makePaginationHtml($paginator); 
 
function makePaginationHtml($paginator)
{
    $last = ceil($paginator->total / $paginator->limit);
    $start = (($paginator->page - $paginator->links) > 0) ? $paginator->page - $paginator->links : 1;
    $end = (($paginator->page + $paginator->links) < $last) ? $paginator->page + $paginator->links : $last;
    $html = '<ul class="' . $paginator->list_class . '">';
    $link = $paginator->link;

    if ($paginator->page > 1) {
        $html .= '<li class=""><a href="' . $link . '&limit=' . $paginator->limit;
        $html .= '&page=' . ($paginator->page - 1) . '">&laquo;</a></li>';
    }
    if ($start > 1) {
        $html .= '<li><a href="' . $link . '&limit=' . $paginator->limit . '&page=1">1</a></li>';
        $html .= '<li class="disabled"><span>...</span></li>';
    }
    for ($i = $start; $i <= $end; $i++) {
        $class = ($paginator->page == $i) ? "active" : "";
        $html .= '<li class="' . $class . '"><a href="' . $link . '&limit=';
        $html .= $paginator->limit . '&page=' . $i . '">' . $i . '</a></li>';
    }
    if ($end < $last) {
        $html .= '<li class="disabled"><span>...</span></li>';
        $html .= '<li><a href="' . $link . '&limit=' . $paginator->limit . '&page=';
        $html .= $last . '">' . $last . '</a></li>';
    }
    if ($paginator->page != $last) {
        $html .= '<li class=""><a href="' . $link . '&limit=' . $paginator->limit;
        $html .= '&page=' . ($paginator->page + 1) . '">&raquo;</a></li>';
    }
    $html .= '</ul>';
    return $html;
}

Wednesday, March 15, 2017

How can I determine whether an entity already exists in the Hibernate session cache

Hibernate use first & second level cache to store database data fetch from database and actually its Hibernate Session. So when your read data from database it stores in Hibernate Session. There is a separate Hibernate Session for each request. Sometimes we need to identify if any object exists in session or not. Below is a simple code snippet to determine if any object exists in current Hibernate Session or not. The most important thing is that you must use proxy to reference the object to check.


package com.pkm

import grails.util.Holders
import org.hibernate.SessionFactory
import org.hibernate.engine.spi.EntityKey
import org.hibernate.stat.SessionStatistics

/**
 * Created by pritom on 15/03/2017.
 * Session.html#getStatistics
 * SessionStatistics.html#getEntityKeys
 */
class HibernateSessionUtil {
    private static SessionFactory sessionFactory

    public static void main(String[] args) {
        def domainInstance = "DomainClass".proxy(100L)
        checkIfObjectExistsInSession(domainInstance)
    }

    static Boolean checkIfObjectExistsInSession(def domainInstance) {
        SessionStatistics sessionStatistics = sessionFactory.currentSession.getStatistics()
        println("Total ${sessionStatistics.getEntityKeys().asList().size()} Object Exists in Session")
        Boolean exists = false
        sessionStatistics.getEntityKeys().asList().find { EntityKey entityKey ->
            println("EntityName=${entityKey.entityName},EntityId=${entityKey.identifier.toString()}")
            if (domainInstance.class.canonicalName.equals(entityKey.entityName) &&
                    domainInstance.id.toString().equals(entityKey.identifier.toString())) {
                exists = true
            }
        }
        return exists
    }

    static {
        sessionFactory = sessionFactory ?: (sessionFactory = getBean(SessionFactory))
    }

    static <T> T getBean(Class<T> requiredType) {
        try {
            return Holders.applicationContext.getBean(requiredType)
        }
        catch (Exception e) {
            return null
        }
    }
}

Saturday, March 11, 2017

Manage Database Transactions in Laravel

Laravel is a strong php based framework today. Its very important to main transactions when you are working with database in your application. If you don't maintain transaction level then you have high probability to loose your data sometimes. So its nothing more to do to handle this situation. Below is a small example how to do this:

DB::transaction(function() use($p1, $p2) {
    $data = array(
        "value_1" => "Value 1",
        "value_2" => "Value 2"
    );
    $insert_id = DB::table('table_name')->insertGetId($data);
    if($insert_id) {
        throw new Exception("Error");
    }

    $data = array(
        "value_1" => "Value 1",
        "value_2" => "Value 2"
    );
    $insert_id = DB::table('table_name_2')->insertGetId($data);
    if($insert_id) {
        throw new Exception("Error");
    }
});


So, if any error occurs or exception thrown by us manually all transaction will be roll back automatically. So all 2 entries will be persist on database together or nothing will be on database.

Escape raw SQL queries in Laravel

Laravel is a strong php based framework today. Laravel has a strong query builder which handle escaping of SQL parameters. But sometimes we need to handle this situation ourselves. So we need to have the capability to handle this situation. We can do this easily using Laravel built-in function as below one line code:

DB::connection()->getPdo()->quote("TEXT 'TO" HANDLE");

Will output like:

'TEXT \'TO\" HANDLE' and MySQL will never mind with this.

Thursday, March 9, 2017

How to Install CakePHP in XAMPP

CakePHP is a free, open-source, rapid development framework for PHP. CakePHP is most popular PHP frameworks today.

The very first thing is to need download CakePHP from here
Then extract it in xampp/htdocs folder as below screenshot:


Next is to browse application: http://localhost/cake/ which will look like below screenshot:


Now open "C:\xampp\htdocs\cake\app\Config\core.php" and change value of following properties "Security.salt" and "Security.cipherSeed".

It will remove first 2 errors.

Then its time to connect the application to MySQL database. To do so first rename the file "C:\xampp\htdocs\cake\app\Config\database.default.php" to "C:\xampp\htdocs\cake\app\Config\database.php" and edit the file as follows:

class DATABASE_CONFIG {
    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => '',
        'database' => 'cake',
        'prefix' => '',
        'encoding' => 'utf8',
    );
}


And finally:

To change the content of home page, edit: APP/View/Pages/home.ctp.
To change layout, edit: APP/View/Layouts/default.ctp.
You can also add some CSS styles for your pages at: APP/webroot/css.

Monday, March 6, 2017

Illegal mix of collations for operation 'UNION'

I don't know for how many reason this error occurred but I found it when going to create a view using two tables using UNION. 

There are different ways to solve this problem. You can solve it by compress the value and then decompress as UNCOMPRESS(COMPRESS(x.name)) AS name.

You have another way to fix this problem. You can use first hex the value and then unhex as UNHEX(HEX(x.name)) AS name.

And finally, to fix this, you need to replace some column references in the SELECT list (in one or more of the queries) with an expression, something like CONVERT(name USING UTF8) AS name.

Some more convert functions are listed below:
CONVERT('2014-02-28', DATE)
CONVERT('2014-02-28 08:14:57', DATETIME)
CONVERT('08:14:57', TIME)
CONVERT(125, CHAR)
CONVERT(4-6, SIGNED)
CONVERT(4-6, UNSIGNED)
CONVERT('4', BINARY)
CONVERT('Some String' USING UTF8)
CONVERT('Some String' USING ASCII)
CONVERT('Some String' USING LATIN1)
CONVERT(x.price, DECIMAL)
CONVERT(x.price, DECIMAL(10,2))

MySQL: Create view from two tables with different column names

Its very important to create MySQL view from two or more tables with different column names. It is not mandatory but we sometime need it hardly. This can be done using UNION each table. Union's must have same columns in the same order across all sections. You should explicitly select/declare the null columns in each part of the union. You can use normal JOIN on each part.

Views in MySQL are two types: MERGE or TEMPTABLE. MERGE is simply a query expansion with appropriate aliases and behave as well as the base table. TEMPTABLE is just what it sounds like, the view puts the results into a temporary table before running the WHERE clause, and there are no indexes on it. It cause some performance impact. 

The default option is UNDEFINED, which determined by MySQL to select the appropriate algorithm. MySQL first try to use MERGE because it is more efficient than TEMPTABLE. 

If the MERGE algorithm cannot be used (determined by MySQL itself), a temporary table must be used instead (This algorithm is TEMPTABLE). MERGE cannot be used if the view contains any of the following constructs (Aggregate function or UNION): 

SUM
AVG
DISTINCT
GROUP BY
HAVING
LIMIT
UNION or UNION ALL


And the final example is as follows:

CREATE OR REPLACE ALGORITHM=MERGE VIEW MY_VIEW AS
SELECT test1.id AS _id, test1.name AS _name, test1.roll AS _roll from test1
UNION
SELECT test2.id AS _id, test2.type AS _name, NULL AS _roll from test2