Wednesday, March 19, 2014

Prestashop / Tpl file tips

Assign a variable value in controller
$value = "Test value";

$this->context->smarty->assign('variable',$value)

To get the variable value in tpl file
{$variable}

If conditions
{if $value}

your code

{/if}

foreach in tpl
{foreach $val as $k=>$v}

your code

{/foreach}
forloop in tpl
{for $foo=1 to 5}
your code
{/for}

Friday, March 14, 2014

Hide the page links in the pagination in Codeigniter

Config options are set as :

 $this->load->library('pagination');
    $config['base_url']    = "/blog/index/$tid/";
    $config['total_rows']  = $num_items;
    $config['per_page']    = $max_items;
    $config['first_link']  = FALSE;
    $config['last_link']   = FALSE;
    $config['uri_segment'] = 4;
    $config['use_page_numbers'] = TRUE;
    $config['display_pages'] = TRUE;
    $config['num_links']     = 1; # this doesn't work
    $config['prev_link']     = 'Previous';
    $config['next_link']     = 'Next';
    $config['cur_tag_open']  = '';
    $config['cur_tag_close'] = '';
    $config['full_tag_open'] = '
'; $config['full_tag_close']= '
'; $this->pagination->initialize($config); $this->outputData['pagination'] = $this->pagination->create_links();

   


OUTPUT :  Prev 1 2 4 3 Next

And if I turn off display_pages I get:

OUTPUT :  Prev Next

Simply way to modify pagination like this in Codeigniter.

Wednesday, March 12, 2014

jquery simple pagination

Jquery simple pagination. Here the following steps.

Step 1 :

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//how much items per page to show
var show_per_page = 5;
//getting the amount of elements inside content div
var number_of_items = $('#content').children().size();
//calculate the number of pages we are going to have
var number_of_pages = Math.ceil(number_of_items/show_per_page);

//set the value of our hidden input fields
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);

//now when we got all we need for the navigation let's make it '

/*
what are we going to have in the navigation?
- link to previous page
- links to specific pages
- link to next page
*/
var navigation_html = '<a class="previous_link" href="javascript:previous();">Prev</a>';
var current_link = 0;
while(number_of_pages > current_link){
navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
current_link++;
}
navigation_html += '<a class="next_link" href="javascript:next();">Next</a>';

$('#page_navigation').html(navigation_html);

//add active_page class to the first page link
$('#page_navigation .page_link:first').addClass('active_page');

//hide all the elements inside content div
$('#content').children().css('display', 'none');

//and show the first n (show_per_page) elements
$('#content').children().slice(0, show_per_page).css('display', 'block');

});

function previous(){

new_page = parseInt($('#current_page').val()) - 1;
//if there is an item before the current active link run the function
if($('.active_page').prev('.page_link').length==true){
go_to_page(new_page);
}

}

function next(){
new_page = parseInt($('#current_page').val()) + 1;
//if there is an item after the current active link run the function
if($('.active_page').next('.page_link').length==true){
go_to_page(new_page);
}

}
function go_to_page(page_num){
//get the number of items shown per page
var show_per_page = parseInt($('#show_per_page').val());

//get the element number where to start the slice from
start_from = page_num * show_per_page;

//get the element number where to end the slice
end_on = start_from + show_per_page;

//hide all children elements of content div, get specific items and show them
$('#content').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

/*get the page link that has longdesc attribute of the current page and add active_page class to it
and remove that class from previously active page link*/
$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');

//update the current page input field
$('#current_page').val(page_num);
}

</script>

Step 2 :

<style>
#page_navigation a{
padding:3px;
border:1px solid gray;
margin:2px;
color:black;
text-decoration:none
}
.active_page{
background:darkblue;
color:white !important;
}
</style>
</head>

Step 3 :
<!-- the input fields that will hold the variables we will use -->
<input type='hidden' id='current_page' />
<input type='hidden' id='show_per_page' />

<!-- Content div. The child elements will be used for paginating(they don't have to be all the same,
you can use divs, paragraphs, spans, or whatever you like mixed together). '-->
<div id='content'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>
<p>Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p>
<p>Pellentesque ac sem ac sem tincidunt euismod.</p>
<p>Duis hendrerit purus vitae nibh tincidunt bibendum.</p>
<p>Nullam in nisi sit amet velit placerat laoreet.</p>
<p>Vestibulum posuere ligula non dolor semper vel facilisis orci ultrices.</p>
<p>Donec tincidunt lorem et dolor fringilla ut bibendum lacus fringilla.</p>
<p>In non eros eu lacus vestibulum sodales.</p>
<p>Duis ultrices metus sit amet sem adipiscing sit amet blandit orci convallis.</p>
<p>Proin ullamcorper est vitae lorem mollis bibendum.</p>
<p>Maecenas congue fringilla enim, tristique laoreet tortor adipiscing eget.</p>
<p>Duis imperdiet metus et lorem venenatis nec porta libero porttitor.</p>
<p>Maecenas lacinia lectus ac nulla commodo lacinia.</p>
<p>Maecenas quis massa nisl, sed aliquet tortor.</p>
<p>Quisque porttitor tellus ut ligula mattis luctus.</p>
<p>In at mi dolor, at consectetur risus.</p>
<p>Etiam id erat ut lorem fringilla dictum.</p>
<p>Curabitur sagittis dolor ac nisi interdum sed posuere tellus commodo.</p>
<p>Pellentesque quis magna vitae quam malesuada aliquet.</p>
<p>Curabitur tempus tellus quis orci egestas condimentum.</p>
<p>Maecenas laoreet eros ac orci adipiscing pharetra.</p>
<p>Nunc non mauris eu nibh tincidunt iaculis.</p>
<p>Ut semper leo lacinia purus hendrerit facilisis.</p>
<p>Praesent et eros lacinia massa sollicitudin consequat.</p>
<p>Proin non mauris in sem iaculis iaculis vel sed diam.</p>
<p>Nunc quis quam pulvinar nibh volutpat aliquet eget in ante.</p>
<p>In ultricies dui id libero pretium ullamcorper.</p>
<p>Morbi laoreet metus vitae ipsum lobortis ultrices.</p>
<p>Donec venenatis egestas arcu, quis eleifend erat tempus ullamcorper.</p>
<p>Morbi nec leo non enim mollis adipiscing sed et dolor.</p>
<p>Cras non tellus enim, vel mollis diam.</p>
<p>Phasellus luctus quam id ligula commodo eu fringilla est cursus.</p>
<p>Ut luctus augue tortor, in volutpat enim.</p>
<p>Cras bibendum ante sed erat pharetra sodales.</p>
<p>Donec sollicitudin enim eu mi suscipit luctus posuere eros imperdiet.</p>
<p>Vestibulum mollis tortor quis ipsum suscipit in venenatis nulla fermentum.</p>
<p>Proin vehicula suscipit felis, vitae facilisis nulla bibendum ac.</p>
<p>Cras iaculis neque et orci suscipit id porta risus feugiat.</p>
<p>Suspendisse eget tellus purus, ac pulvinar enim.</p>
<p>Morbi hendrerit ultrices enim, ac rutrum felis commodo in.</p>
<p>Suspendisse sagittis mattis sem, sit amet faucibus nisl fermentum vitae.</p>
<p>Nulla sed purus et tellus convallis scelerisque.</p>
<p>Nam at justo ut ante consectetur faucibus.</p>
<p>Proin dapibus nisi a quam interdum lobortis.</p>
<p>Nunc ornare nisi sed mi vehicula eu luctus mauris interdum.</p>
<p>Mauris auctor suscipit tellus, at sodales nisi blandit sed.</p>

</div>

<!-- An empty div which will be populated using jQuery -->
<div id='page_navigation'></div>
</body>

OUTPUT :

Thanks for the helpful site click .


Tuesday, March 04, 2014

Mysql indexes

1)   Database index is a data structure that improves the speed of operations in a table.

2)   Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.

3)   INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to insert or update index values as well.

There are four types of statements for adding indexes to a table:
                                           
            1) PRIMARY KEY
            2) UNIQUE 
            3) INDEX or KEY
            4) FULLTEXT                  

SYNTAX :

 ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.

· ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).


· ALTER TABLE tbl_name ADD INDEX index_name (column_list): This adds an ordinary index in which any value may appear more than once.


· ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): This creates a special FULLTEXT index that is used for text-searching purposes.

Differences
·       KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for making sure certain queries can run quickly.

·       UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, youmay find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

·       PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.
·         FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

How do you add an index?

To add a correct index, identify the query that executes slowly, and then look at the “where” clause of that query – which fields are used for filtering?  These are probably the ones that should be indexed. For example:

SELECT first_name, last_name FROM contacts WHERE city = “Los Angeles”;

Here, if there isn't already an index on the column “city” (and if the table is more than a few rows), the index should be added:

ALTER TABLE contacts ADD KEY (city);

If you are filtering by multiple fields, like:

SELECT first_name, last_name FROM contacts WHERE status = “active” AND delivery_method = “mail” AND city = “Los Angeles”;

… then you should create a “composite” index:

ALTER TABLE contacts ADD KEY (status, delivery_method, city);

This index will speed up queries that filter by either all of these fields or a subset of them, starting from the left column, as specified in the ALTER TABLE statement.
That means the following where clauses will use the index:

… WHERE status = “active” AND delivery_method = “mail” AND city = “Los Angeles”;
… WHERE status = “active” AND delivery_method = “mail”;
… WHERE status = “active”;

In contrast, where clauses like these will not use this composite index:

… WHERE city = “Los Angeles”;

… WHERE delivery_method = “mail” AND city = “Los Angeles”;


You would have to create another index with the necessary column(s).

Example:

EXPLAIN SELECT first_name, last_name FROM contacts WHERE city = “Los Angeles”;

(I created a small test table consisting of five rows)

mysql> EXPLAIN SELECT first_name, last_name FROM contacts WHERE city = "Los Angeles"\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: contacts
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 5
Extra: Using where
1 row in set (0.00 sec)

As you see here, possible_keys and keys are set to NULL, which means the MySQL optimizer didn’t find any keys to use. An important column in the EXPLAIN output is “rows”, which is an estimate of how many rows MySQL has to read to find the desired result. Here, it is five, which are all rows in the table. That means the database has to perform a full table scan.

Let’s add an index:

ALTER TABLE contacts ADD KEY (city);

That brings us to another important command – you can use “SHOW INDEX FROM <table>” to find out which indexes are already created on a particular table:

mysql> SHOW INDEX FROM contacts\G
*************************** 1. row ***************************
Table: contacts
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 5
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:

*************************** 2. row ***************************

Table: contacts
Non_unique: 1
Key_name: city
Seq_in_index: 1
Column_name: city
Collation: A
Cardinality: 5
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
2 rows in set (0.00 sec)

Here we see two rows – the second row shows the newly added index on the column city. Now if we run the same EXPLAIN-statement again, we get a different – better – result:

mysql> EXPLAIN SELECT first_name, last_name FROM contacts WHERE city = "Los Angeles"\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: contacts
type: ref
possible_keys: city
key: city
key_len: 103
ref: const
rows: 1
Extra: Using where
1 row in set (0.00 sec)


Notice that the possible_keys and keys columns both contain the field “city”, which means that MySQL was able to use this index to satisfy the query. Another important difference is the number of rows MySQL estimates it will have to search – it’s now only one!  The database is now going directly from the index to the row (which is referenced by the primary key).

Storage engines:
MySQL supports several storage engines that act as handlers for different table types. MySQL storage engines include both those that handle transaction-safe tables and those that handle non-transaction-safe tables:

MYISAM:
1.    MYISAM supports Table-level Locking
2.    MyISAM designed for need of speed
3.    MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
4.    MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
5.    MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
6.    MYISAM supports fulltext search
7.    You can use MyISAM, if the table is more static with lots of select and less update and delete.


mysql> SHOW ENGINES\G
*************************** 1. row ***************************
Engine : MyISAM
Support: DEFAULT
Comment: Default engine as of MySQL 3.23 with great performance

     INNODB :
1.    InnoDB supports Row-level Locking
2.    InnoDB designed for maximum performance when processing high volume of data
3.    InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
4.    InnoDB stores its tables and indexes in a tablespace
5.    InnoDB supports transaction. You can commit and rollback with InnoDB


mysql> SHOW ENGINES\G
*************************** 1. row ***************************
Engine : InnoDB
Support: YES
Comment: Supports transactions, row-level locking,and foreign keys

Monday, March 03, 2014

MUL mean in MySQL for the key

In any case, there are three possible values for the “Key” attribute:
  1. PRI
  2. UNI
  3. MUL
The meaning of PRI and UNI are quite clear:
  • PRI=> primary key
  • UNI=> unique key
The third possibility, MUL, (which you asked about) is basically an index that is neither a primary key nor a unique key. The name comes from “multiple” because multiple occurences of the same value are allowed. Straight from the MySQL documentation:

“If Key is MUL, the column is the first column of a non-unique index in which multiple occurrences of a given value are permitted within the column.”


“If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order PRI, UNI, MUL.”