Monday, April 7, 2014

WordPress dropdown menu with wp_nav_menu and CSS

WordPress 3.0 came with quite a number of awesome and useful features. That includes native navigational menus, which can be customized through the WordPress admin. (Dashboard –> Appearance –> Menus) . Many themes released nowadays support native menus. Let us learn how to add some Native menu support.
This is part 1 of the dropdown menu series.
To check whether your theme has native menu support, Proceed to “Wordpress admin-> Appearance –> Menus” (WordPress 3.0+ only) . If there is no support, following message will be displayed.
1_no_menu_support
Look! No native menu support.
We can add the support by following through the below guide. Since it is not advisable to play with your blog’s theme, I have made a simple theme just for this purpose. It is a mod of Famous Kubrick of WP 2.0, and is named Axtra.  If possible, definitely try this on a local server in yourMac or windows.
{filelink=1}

wp_page_menu(); aka WordPress 3.0+ native menus support

wp_nav_menu() function does the work of displaying the wordpress menus that can be completely and easily customized through the admin. [codex reference]
Following code displays the menu.
?
1
<?php wp_nav_menu(); ?>
Like most wordpress functions do, wp_nav_menu() accepts arguments.
?
1
<?php wp_nav_menu(array( ‘theme_location’ => ‘Main-Menu’)); ?>
Complete arguments list is available in WordPress codex, Below are the options that we will be using through out this walkthrough.
  1. theme_location : Theme location, i.e. Location of the menu in the theme structure.
  2. menu_class: CSS class for the menu. (Default is ‘menu_class’ => ‘menu’).
  3. fallback_cb : Fallback wordpress function to call, when wp_nav_menu is un available. default is wp_list_pages.
  4. container_id : CSS ID to be assigned to the container(default is DIV tag) that wraps around the menu.
  5. container_class : Similar to above, but this is CSS class.

Adding wp_nav_menu support to your theme

This involves the following procedure.
  1. Register the menu : This can be done using register_nav_menu orregister_nav_menus and initializing them.
  2. Display the menu : Add wp_nav_menu function to the theme, wherever you want the menu to appear.
  3. Style the menu : The key is adding the menu CSS class to wp_nav_menu and using that class with the CSS or JS dropdown solution.

Registering the menu

* NOTE: Before registering the menus add (<?php wp_head(); ?>) in your header before the header closing tag.

Open the theme’s function.php. If it is not present in your theme’s root directory, create a new file with the same name. Always name it in lowercase.
First thing to do is registering the menu location, through register_nav_menus() [Codex reference]
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// Create a function for register_nav_menus()
function add_wp3menu_support() {
register_nav_menus(
        array(
        'main-menu' => __('Main Navigation'),
        'another-menu' => __('Another Navigation')
        )
     );
}
//Add the above function to init hook.
add_action('init', 'add_wp3menu_support');
Good. Now theme has two menus, first one – registered as  “main-menu” – used to display the Main navigation below the header, and second – “another-menu” which may be used for diverse purposes (For e.g. add a menu to sidebar, custom post). The menus are to be initialized with the theme through wp_head() hook.

Display the menu

Now the registered menus need to be displayed. Here comes wp_nav_menu to the rescue. Insert the following code in the theme, where you want the menu to appear.
Usual location would be just below the header. I chose to include this in header.php , below the header div tag. I also added a div container around the menu with the CSS ID “navigation” (which can be used later for centering the menus).
?
1
2
3
4
5
6
<!-- a container that wraps around.-->
<div id="navigation">
<?php wp_nav_menu(); //displays the menu?>
</div><!-- end #navigation -->
Well, this displays the menu. Now we have two concerns. First – we registered two menus and second – we need to add dropdown menus in the next step. wp_nav_menu has got arguments that we can make use of.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
<div id="navigation">
<?php
          wp_nav_menu( array(
    'theme_location' => 'main-menu', // Setting up the location for the main-menu, Main Navigation.
    'menu_class' => 'dropdown', //Adding the class for dropdowns
    'container_id' => 'navwrap', //Add CSS ID to the containter that wraps the menu.
    'fallback_cb' => 'wp_page_menu', //if wp_nav_menu is unavailable, WordPress displays wp_page_menu function, which displays the pages of your blog.
    )
      );
?>
</div>
Let us look at the above code.
  • ‘theme_location’ refers to the location of the menu in the theme.
  • ‘menu_class’ refers to CSS class that is going to be used for dropdown menu.
  • Similarly ‘container_id’ is the CSS ID for the div that surrounds the Navigation.
  • ‘fallback_cb’ points to the function that will be used in case wp_nav_menu is not available. Default for ‘fallback_cb’ is the function wp_list_pages().
This completes setting up the “main-menu”. Similarly setup the “another-menu” for better idea.
Congratulations. Now your theme has wordpress 3.0 Menus support. Now check “Dashboard –> Appearance –> Menus”. The “no support” message is gone! Yes, you should now be able to create custom menus (Hint: Button “Create Menu”).
If you encounter any problems, verify with the included (modified) functions.php and header.php below.
{filelink=2}

Styling the menu with Superfish and similar

This is covered in a separate article here.

Creating a Menu via WordPress admin

  1. Proceed to “WordPress admin –> Appearance –> Menus”.
  2. Enter the menu name and Click “Create Menu”. You should now see a message “Theyour_menu_name_here menu has been successfully created.”
  3. Now you can add custom links, pages or categories to your menu.
        1. In the custom Links field, you can enter the URL and Label(name it goes by) and click “Add to Menu”.
        2. In the Pages, Check those you need to appear in menu and click “Add to Menu”.
        3. Similarly add those in the categories.
        4. Now click “Save Menu”.
        5. Simply drag above and below to re-order and drag left and right to (un)indent the menu items.
        6. It is simpler and better if you have up to 3 levels of menu.
  4. Look in the first box under “Theme locations”. Now select the menu you just created in the combo box “Primary Navigation”. Remember, We named our “main-menu” as “Primary Navigation”. Click Save.
    menu_added
    Your Menu has been successfully created.
Well done. Now reload and check your index page. Menu appears, but looks hideous.
unstyled_menu
Hmm.. Not quite what we expected.But wait!
Untitled-3
Throwing in some css, Now it looks neat. and with No images.
And the CSS involved, with some explanation.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* The container wrapping ul.dropdown */
#navwrap {
float:left;
width:100%;
background: #600;
background: -moz-linear-gradient( top, #600, #300); /* CSS 3 */
font: 1.0em "Segoe UI", "Lucida Grande", Verdana, Arial, sans-serif;
border-top:1px solid #999;
border-bottom:2px solid #000;
}
/* Top level Unordered list */
ul.dropdown {
list-style:none;
float:left;
width:100%;
padding: 0 10px;
}
ul.dropdown  li{
float:left; /* makes horiz list */
position:relative; /* hey Submenu ULs, appear below! */
}
ul.dropdown a {
padding:12px; /*space the items, occupy entire height too.*/
color:#eee;
text-decoration:none;
text-shadow:0 1px 0 #000;
}
/* Style the link hover */
ul.dropdown li:hover a {
background:#444;
border-top:1px solid #777;
border-bottom: 1px solid #000;
border-right:1px solid #666;
}
/* Displays the link as blocks. */
ul.dropdown li ul a {
display:block;
}
/* sub menus!!  */
ul.dropdown ul {
list-style: none;
margin:0; /* Appear just below the hovering list */
padding:0;
width:200px; /* specify the width. */
position:absolute; /* needed */
z-index:500; /* specify the order */
}
ul.dropdown li ul {
top:27px; /* Positioning:Calc with top level horz list height */
-moz-box-shadow:0 2px 10px #000; /* CSS 3 */
}
ul.dropdown ul ul {
top:0;
left:100%; /* Position the sub menus to right. */
}
ul.dropdown ul li {
float:none; /* umm.. Appear below the previous one. mmkay? */
}
/* Drop Down! */
/* Hide all the dropdowns (submenus) */
ul.dropdown ul,
ul.dropdown li:hover ul ul,
ul.dropdown ul li:hover ul ul
{ display: none; }
/* Display the submenus only when li are hovered */
ul.dropdown li:hover ul,
ul.dropdown ul li:hover ul ,
ul.dropdown ul li ul li:hover ul
{ display: block;}
ul.dropdown li * a:hover {
/* Change color of links when hovered */
background: #600;
background: -moz-linear-gradient( top, #200, #400); /* CSS 3 */
border-bottom:1px solid #900;
border-top:1px solid #222;
}

This article is taken from : http://kav.in/wordpress-dropdown-menu-wp-nav-menu-css/

Thursday, April 3, 2014

Some gamy questions?

Q1: When is a language considered a scripting language?

Ans: 
        Traditionally, when talking about the difference about scripting versus programming, scripts are interpreted and programs are compiled. A language can be executed in different ways - interpreted or compiled (to bytecode or machine code). This does not make a language one or another.


In some eyes, the way you use a language makes it a scripting language (for example, game developers who develop mainly in C++ will script the objects in Lua). Again, the lines are blurred - a language can be used for a programming by one person and the same language can be used for scripting language by another.
Q2: What is the difference between HTML tags DIV and SPAN?
Ans:     
         This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.
                                                                   OR
<div> is a block-level element and <span> is an inline element.
If you wanted to do something with some inline text, <span> is the way to go since it will not introduce line breaks that a <div> would.

Q3: What Differences Between HTML and XHTML?

Ans: 
       The most important difference between the two markup languages is that HyperText Markup Language, or HTML, is an application of SGML (Standard Generalized Markup Language),1 and allows an author to omit certain tags and use attribute minimization.2 The Extensible HyperText Markup Language, or XHTML, is an application of XML (Extensible Markup Language).3 It doesn’t permit the omission of any tags or the use of attribute minimization. However, it provides a shorthand notation for empty elements—for example, we could use <br/> instead of <br></br>—which HTML does not. A conforming XML document must be well formed, which, among other things, means that there must be an end tag for every start tag, and that nested tags must be closed in the right order.4 When an XML parser encounters an error relating to the document’s well-formedness, it must abort, whereas an HTML parser is expected to attempt to recover and continue.

There are three areas in which the differences between HTML and XHTML affect our use of CSS:

case sensitivity
optional tags
properties for the root element

Q4: What are Associative Arrays?

Ans:
      Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array: 

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

The named keys can then be used in a script:

Q5: What is htaccess?

Ans:
       Hypertext Access, commonly shortened to htaccess, is a powerful configuration file which controls the directory it is placed in and all the subdirectories underneath it.
htaccess, useful feature allowing webmasters to control how many aspects of their website works.

Using .htaccess files lets you control the behavior of your site or a specific directory on your site. For example, if you place an .htaccess file in your root directory, it will affect your entire site (www.coolexample.com). If you place it in a /content directory, it will only affect that directory (www.coolexample.com/content).

.htaccess works on our Linux servers.

Using an .htaccess file, you can:

Customize the Error pages for your site.
Protect your site with a password.
Enable server-side includes.
Deny access to your site based on IP.
Change your default directory page (index.html).
Redirect visitors to another page.
Prevent directory listing.
Add MIME types.
.htaccess files are a simple ASCII text file with the name .htaccess. It is not an extension like .html or .txt. The entire file name is .htaccess.

Q6: What is a RECURSIVE Function in PHP?

Ans:
      Definition: A recursive function is a function that calls itself.

A bit more in depth:
                   If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

Q7: Difference between MVC and 3 tier Architecture?

Ans: 
      At first glance, the three tiers may seem similar to the model-view-controller (MVC) concept; however, topologically they are different. A fundamental rule in three tier architecture is the client tier never communicates directly with the data tier; in a three-tier model all communication must pass through the middle tier. Conceptually the three-tier architecture is linear. However, the [model-view-controller] MVC architecture is triangular: the view sends updates to the controller, the controller updates the model, and the view gets updated directly from the model.

Q8: How to find second highest or maximum salary of Employee in MySql?

Ans: 
       There are many ways to find second highest salary based upon which database you are using as different database provides different feature which can be used to find second maximum or Nth maximum salary of employee. Well this question can also be generalized with other scenario like finding second maximum age etc. To find second highest salary independent of databases or you may call in ANSI SQL and other SQL queries which uses database specific feature to find second maximum salary.

SQL query to find second maximum salary of Employee

In this section we will write SQL query to get second highest salary of Employee. Before writing query its good to be familiar with schema as well as data in table. Here is the Employee table we will be using this SQL example:

mysql> SELECT * FROM Employee;
+--------+----------+---------+--------+
| emp_id | emp_name | dept_id | salary |
+--------+----------+---------+--------+
| 1      | James    | 10      |   2000 |
| 2      | Jack     | 10      |   4000 |
| 3      | Henry    | 11      |   6000 |
| 4      | Tom      | 11      |   8000 |
+--------+----------+---------+--------+
4 rows IN SET (0.00 sec)

If you look data, you will find that second maximum salary in this case is 6000 and employee name is Henry. Now let’s see some SQL example to find out this second maximum salary.

Second maximum salary using sub query and IN clause

Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of sub query.

mysql> SELECT max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary) FROM Employee);
+-------------+
| max(salary) |
+-------------+
|        6000 |
+-------------+
1 row IN SET (0.00 sec)

Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:

mysql> SELECT max(salary) FROM Employee WHERE salary < (SELECT max(salary) FROM Employee);
+-------------+
| max(salary) |
+-------------+
|        6000 |
+-------------+
1 row IN SET (0.00 sec)

Both of above SQL example will work on all database including Oracle, MySQL, Sybase and SQL Server as they are written using standard SQL keywords. But sometime you can also use database specific features like TOP keyword of SQL Server or Sybase database to find out second highest salary of Employee.

Second highest salary using TOP keyword of Sybase or SQL Server database

TOP keyword of Sybase and SQL Server database is used to select top record or row of any result set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as shown below.

SELECT TOP 1 salary FROM ( SELECT TOP 2 salary FROM employees ORDER BY salary DESC) AS emp ORDER BY salary ASC

Here is what this SQL query is doing : First find out top 2 salary from Employee  table and list them in descending order, Now second highest salary of employee is at top so just take that value. Though you need to keep in mind of using distinct keyword if there are more than one employee with top salary, because in that case same salary will be repeated and TOP 2 may list same salary twice.

Second maximum salary using LIMIT keyword of MYSQL database

LIMIT keyword of MySQL database is little bit similar with TOP keyword of SQL Server database and allows to take only certain rows from result set. If you look at below SQL example, its very much similar to SQL Server TOP keyword example.

mysql> SELECT salary  FROM (SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2) AS emp ORDER BY salary LIMIT 1;
+--------+
| salary |
+--------+
|   6000 |
+--------+
1 row IN SET (0.00 sec)



That’s on How to find second highest salary of Employee using SQL query. 

Sunday, March 30, 2014

PHP array pagination

This is a basic script to take an array and and generate a paginated list of items. This is quite an obscure example because a real world example would probably include lots more data.
I'd also like to say, if your working with databases then I would suggest using a database pagination script that uses limits etc to optimise the speed of the query etc. If your looking to paginate a small data set then this should be fine.
Pretty simple setup:

Include the class:

// Include the pagination class
include 'pagination.class.php';

Here i'm throwing in some test date (you will need to provide your own)

// some example data
foreach (range(1, 100) as $value) {
  $products[] = array(
  'Product' => 'Product '.$value,
  'Price' => rand(100, 1000),
  );
}

Then this is how to output of the page data and page numbers.

// If we have an array with items
if (count($products)) {
    // Create the pagination object
    $pagination = new pagination($products, (isset($_GET['page']) ? $_GET['page'] : 1), 15);
    // Parse through the pagination class
    $productPages = $pagination->getResults();
    // If we have items 
    if (count($productPages) != 0) {
        // Create the page numbers
        echo $pageNumbers = '<div class="numbers">'.$pagination->getLinks().'</div>';
        // Loop through all the items in the array
        foreach ($productPages as $productArray) {
            // Show the information about the item
            echo '<p><b>'.$productArray['Product'].'</b> &nbsp; &pound;'.$productArray['Price'].'</p>';
        }
        // print out the page numbers beneath the results
        echo $pageNumbers;
    }
}
There are two other configurations that currently exist:
If you would like to show "<< first" and "last >>" links to take you to the first and last page.
$pagination->setShowFirstAndLast(true);
The default separator for the page numbers is an empty string, you can overwrite this to be anything you like.
$pagination->setMainSeperator(' | ');
It's pretty simple.
Download Complete Script in Zip from here: https://app.box.com/s/8an37ogzo915p3rnz3ej
This article Taken from: http://lotsofcode.com/php-array-pagination/

Saturday, March 29, 2014

Php Array Pagination Script

///////////////FILLING ARRAY WITH DUMMY DATA////////////////////
$key = array();
for($i=0; $i<200; $i++)
{
 //fill array data
 $key[] = "num = ".$i;
}
////////////////////////////////////////////////////////////////

/////////////////////START OF ARRAY PAGINATION CODE/////////////////////
$ptemp="http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$pt=explode('&',$ptemp);
if (strpos($ptemp,'pageno'))
 array_pop($pt);
$pt=implode('&',$pt);
$ptemp=$pt;
$array=$key; // REPLACE $KEY WITH YOUR ARRAY VARIABLE
$page = $_REQUEST['pageno'];

$currentpage = isset($page) ? (integer)$page : 1;
$numperpage = 10; //NUMBER OF RECORDS TO BE DISPLAYED PER PAGE

$total = count($array);
$numofpages = ceil($total / $numperpage); //TOTAL NUMBER OF PAGES

if(isset($array))
{
    if (($currentpage > 0) && ($currentpages <= $numofpages))
 {
        //STARTING LOOP FOR ARRAY DATA
        $start = ($currentpage-1) * $numperpage;
        for($i=$start;$i<=($numperpage+$start-1);$i++) 
  {
            ///////////PLACE YOUR CODE HERE//////////////////////////
            echo $array[$i] .'
';
   ////////////////////////////////////////////////////////
        }
 }
}
if ($currentpage != 1) 
{ //GOING BACK FROM PAGE 1 SHOULD NOT BET ALLOWED
 $previous_page = $currentpage - 1;
 $previous = ' < ';    
}    
$pages = '';
for ($a=1; $a<=$numofpages; $a++)
{
  if ($a == $currentpage) 
 $pages .= $a .' ';
  else 
 $pages .= ''. $a .' ';
}
$pages = substr($pages,0,-1); //REMOVING THE LAST COMMA (,)

if ($currentpage != $numofpages) 
{ //GOING AHEAD OF LAST PAGE SHOULD NOT BE ALLOWED
 $next_page = $currentpage + 1;
 $next = '  >';
}
echo '

'. $previous . $pages . $next; //PAGINATION LINKS
/////////////////////END OF ARRAY PAGINATION CODE/////////////////////

Monday, March 24, 2014

How to calculate difference in days between two dates in MySQL

Let's say we have a MySQL table where one column (date or datetime type) is namedactivated and contains dates in one of the YYYY-MM-DD or YYYY-MM-DD HH:MM:SSformats from the past and we need to calculate the difference in days since that date untill current date for each row.

First let's see a preview of the activated column:
mysql> SELECT activated FROM table_dates LIMIT 0,5;
+--------------+
| activated     |
+--------------+
| 2007-06-06 |
| 2007-10-15 |
| 2007-10-17 |
| 2007-10-18 |
| 2007-10-19 |
+--------------+
5 rows in set (0.00 sec)
mysql>
so we see dates lik 06th of June, 15th of October and so on. Now, let's calculate the difference between these dates and current date:

mysql> SELECT DATEDIFF(CURDATE(), activated) AS intval FROM table_dates LIMIT 0,5;
+--------+
| intval   |
+--------+
|    259  |
|    128  |
|    126  |
|    125  |
|    124  |
+--------+
5 rows in set (0.00 sec)
so the difference in days between 6th of June and present day is 259 days. Same with the others.
I used in the queries above two MySQL date functions: DATEDIFF() and CURDATE().

Friday, March 21, 2014

mysql_fetch_row() vs mysql_fetch_assoc() vs mysql_fetch_array()

What will the different functions return?

All of the mentioned functions will return an array, the differences between them is what values that are being used as keys in the returned object.
  • This function will return a row where the values will come in the order as they are defined in the SQL query, and the keys will span from 0 to one less than the number of columns selected.
  • This function will return a row as an associative array where the column names will be the keys storing corresponding value.
  • This function will actually return an array with both the contents of mysql_fetch_rowand mysql_fetch_assoc merged into one. It will both have numeric and string keys which will let you access your data in whatever way you'd find easiest.
    It is recommended to use either _assoc or _row though.

Thursday, March 20, 2014

What is difference between MYISAM and InnoDB?

The major thing that beginners are curioues to know what are the difference between InnoDB and MyISAM. Below is difference between MYISAM and INNODB hope this will help you out a lot. 

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. 

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


Difference show By below table.

My ISAMInnoDB
Required full text SearchYes
Require TransactionsYes
frequent select queriesYes
frequent insert,update,deleteYes
Row Locking (multi processing on single table)Yes
Relational base designYes

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...