phprockers-logo

Display the custom file in cms block to frontend/backend in Magento

0 comments
Below coding can be used to show CMS block in Frontend.

Ref. Path :  app/design/frontend/base/default/template/callouts/left_col.phtml or right_col.phtml.

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_id')->toHtml(); ?>

Setting in Backend:

First Go to CMS and create a static page. Here we take "identifier" id from static block and put this id to above coding inside setBlock_id. And inside content we have put following line for calling our own block coding file,

{{block type="core/template" name="leftnav_menu" template="menu/menu.phtml"}}

Finally we have saved the file and this file is running in frontend inside the block.


Database connection in Joomla 2.5

0 comments
We have easy to connect database in joomla 2.5. Using below function
we have to connect database wherever you want in joomla folder.
 
$db =& JFactory::getDBO();

What is MVC in Joomla?

1 comments
MVC - Model-View-Component

“MVC consists of three kinds of objects. The Model is the application object, the View isits screen presentation, and the Controller defines the way that the user interface reacts tothe user input.

Create a custom page template in wordpress

0 comments
we have a sidebar on all of pages in wordpress website, but we want to have a page that doesn’t have a sidebar. Here is how we create a custom page template without a sidebar in wordpress:

1)   Create a new file in wordpress theme folder and name it withoutSidebar.php.

2)   Open page.php and copy all of the code and paste it into the newly created withoutSidebar.php.

3)   Make any changes that you would like to withoutSidebar.php. In this example we are going to remove the sidebar, so find the code that calls the sidebar (<?php include(‘sidebar.php’); ?>) and remove it.

4)   You may also want to find the div that contains the main container and add a width style to make it cover the whole page.

5)   Finally, and most importantly, add the following line of code to the top of the page. This code is used to tell WordPress that this is a custom template. Without this code, WordPress would not be able to find the template:


<?php
    /*
   Template Name: without Sidebar
   */
 ?>

6)     Save this file and upload it to your server.

Difference between Primary Key and Unique key in mysql?

0 comments
Difference between Primary Key and Unique key in mysql/sql/oracle?

SNO Primary Key Unique Key
1 Primary Key does not allow NULLs values in a table Unique Key allows Nulls value in a table
2 Only one primary key will be there in a table More than one unique key will be there in a table
3 Clustered index is created in primary key in a table Non-Clustered index is created in unique key in a table
4 Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist as well as does not allow the duplicates values in the rows of a table. Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values

By default Primary Key creates a Clustered Index on the column as same as Unique Key creates a Nonclustered Index. Another major difference is Primary Key doesn’t allow NULLs, but Unique Key allows NULLs. We can create only one primary key in a table, but a table can have the multiple unique key.

Update query in mysql

0 comments
The syntax for Update the row into tables,

UPDATE
    table_name SET (colname1, colname2, colname3 ...) VALUES (value1,value2,value3,...) WHERE colname = row_values;   

<?php

$con = mysql_connect('localhost', 'root','');
mysql_select_db('dbname', $con) or die(mysql_error());

$query = "UPDATE table_name SET rank="2" WHERE sno = 2";   
$ok = mysql_query($query);

if($ok)
echo "Updated row successfully";
else
echo "Failed to update the row in the table";

?>


sno name marks rank post_of_date
2 krishnan 397 2 09-04-2001
3 PHP Developer 521 36 27-03-2012

Delete query in mysql with php

0 comments
The syntax for Delete the row into tables,

DELETE FROM
    table_name WHERE colname = row_values;    

<?php

$con = mysql_connect('localhost', 'root','');
mysql_select_db('dbname', $con) or die(mysql_error());

$query = "DELETE FROM table_name WHERE sno = 1";    
$ok = mysql_query($query);

if($ok)
echo "Deleted row successfully";
else
echo "Failed to delete the row in the table";

?>



sno name marks rank post_of_date
2 krishnan 397 3 09-04-2001
3 PHP Developer 521 36 27-03-2012

Insert query in mysql with php

0 comments
The syntax for inserting values into tables,

INSERT INTO
    table_name (`col1`, `col2`, `col3`,.....)
    VALUES ('val1', 'val2', 'val3',.....);    

<?php

$con = mysql_connect('localhost', 'root','');
mysql_select_db('dbname', $con) or die(mysql_error());

$query = "INSERT INTO table_name (`sno`, `name`, `marks`, `rank`,`post_of_date`) VALUES ('3', 'PHP Developer', '521', '36',now())";    
$ok = mysql_query($query);

if($ok)
echo "Inserted successfully";
else
echo "Data's are not inserted in to table";

?>



sno name marks rank post_of_date
1 Ram 407 3 09-04-2001
2 krishnan 397 3 09-04-2001
3 PHP Developer 521 36 27-03-2012

Show the content or text when mouse over the link

0 comments

<style type="text/css">
<!--
.box {
background-color: #F4F4F4;
border: 1px solid #CCC;
height: 150px;
width: 225px;
padding: 5px;
display:none;
position:absolute;
}


-->
</style>
<script type="text/javascript" language="JavaScript">
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
if(self.pageYOffset) {
rX = self.pageXOffset;
rY = self.pageYOffset;
}
else if(document.documentElement && document.documentElement.scrollTop) {
rX = document.documentElement.scrollLeft;
rY = document.documentElement.scrollTop;
}
else if(document.body) {
rX = document.body.scrollLeft;
rY = document.body.scrollTop;
}

How to delete checked checkbox rows in php?

0 comments
<?php
if($_REQUEST['btndelete'] != '')
{
    if(!empty($_REQUEST['checkboxstatus'])) {
        $checked_values = $_REQUEST['checkboxstatus'];
        foreach($checked_values as $val) {
            $sqldel = "delete from subscribe where id = '$val'";
            $resdel = mysql_query($sqldel);
            if($resdel)
                $error_log = 1;
            else
                $error_log = 2;
        }
    }
}

How to send the email in php?

0 comments
Easily send the email in php, you have to follow some steps
<?php
    $mail_to = "phprockers.blogspot@gmail.com";
    $mail_subject = "Introducing New concept in PHP";
    $body_content = "Hi <br/> We are introducing new method in php as well as we are teaching php clearly. Please click here and watch <a href='http://phprockers.blogspot.in/'>php tutorial</a>";
    if(mail($mail_to, $mail_subject, $body_content)){
        echo "Email sent successfully";
    } else {
        echo "Email sending problem. Please try again.";
    }
?>

How to send the email with attachment in php?

0 comments
Very simple to send the email with attachment with php validation.

First we have to write html form for upload the attchement.

<form name="uploadRes" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF'];" >
<input type="file" name="resume" id="resume" />
<input type="submit" name="res-submit" id="res-submit" value="Send Resume"  />
</form>

Validation for attaching the file. Here we have to find the file type, then send the email to particular function.

if($_REQUEST['res-submit'] != '') {
    if(!empty($_FILES)) {
        function getExt($file) {
            $dot = strrpos($file, '.') + 1;
            return substr($file, $dot);
        }


How to integrate "xing" share button in your site?

1 comments

Steps:
1.Select The button layout as you want display in your site.
2.Provide the Url for which you are going to display the xing share count.(This is optional)
3.Select the language.
4.Copy the code in the textarea and paste it in your page.
Thats it. The All new Xing share button will be displayed in your site.

How to get the post tags by category name in wordpress?

0 comments
Paste this code wherever you want to get post tags for specific category name in wordpress.

<?php

$cat_name = "Test Cat";
query_posts('category_name='.$cat_name); //give the your category name here.

if (have_posts()) : while (have_posts()) : the_post();
$postTags = get_the_tags();
    if ($postTags) {
        foreach($postTags as $tag) {
            $all_tags[] = $tag -> name;
        }
    }
endwhile; endif;

if(!empty($all_tags)) {
    $unique_tags = array_unique($all_tags); //Removes the duplicates tags in the all_tags_arr array.
    echo '<pre>'.print_r($unique_tags, true).'</pre>';
} else {
    echo "No post tags are available for ".$cat_name." - category";
}

?>

How to get the posts by post tags in wordpress

0 comments
We have easily get the post titles from from the post Id. So We have to try to get the post Id using the post tags.

<?php 
               
global  $wpdb;

$postTags = "Accidents";

//Below query can be used to get the post id using post tags.

$querystr ="SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = (SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = 'post_tag' AND term_id = (SELECT term_id FROM wp_terms WHERE name ='$postTags '))";

$result= $wpdb->get_results($querystr);
//$result have the post id. Now we easily get the post title or post information using post id.

foreach($result as $postid) {

echo get_the_title($postid->object_id).'<br/>';

}

?>

What is normalization?

0 comments
Normalisation is a set of rules and techniques concerned with below:

    1. Identifying relationships among the attributes.
    2. Combining the attributes to form relations.
    3. Combining the relations to form a database.

Normalised relational database gives several benefits to us:

    1. Elimination of redundant data storage in the database.
    2. Close modeling of real world entities, processes, and their  relationships.
    3. Structuring of data so that the model is flexible.

Strip tags in PHP

0 comments
strip_tags() function will return the string with stripped(removed) HTML and PHP tags.

<?php

$string = '<h2>This is PHP Rokcers blogspot.</h2><!-- Comment --> <a href="http://phprockers.blogspot.com/">phprockers</a>';

echo strip_tags($string);

?>

Output:
=======
This is PHP Rokcers blogspot. phprockers

If we want to allow some specific tags in our string, we have to given that tags as parameters in strip_tags function.

<?php

$string = '<h2>This is PHP Rokcers blogspot.</h2><!-- Comment --> <a href="http://phprockers.blogspot.com/">phprockers</a>';

echo strip_tags($string, '<h2><a>');

?>

Output:
=======
<h2>This is PHP Rokcers blogspot.</h2><a href="http://phprockers.blogspot.com/">phprockers</a>

Dynamic upload the multiple files in php with Javascript validation

1 comments
<?php
    $con = mysql_connection() or (mysql_error();
    mysql_db_select("phprockers", $con) or mysql_error();
?>
<html>
<script type="text/javascript" >
    function add_more() {
        var img = document.getElementById("image").value;
        img=parseInt(img)+1;
        var txt = "<br><input type = file name = images"+img+">";
        document.getElementById("image").value=img;
        document.getElementById("files").innerHTML += txt;
    }


    function validate(){
        var img = document.getElementById("image").value;
        img=parseInt(img);

Multiple File uploads in PHP

0 comments
<?php
    $con = mysql_connection() or(mysql_error();

    mysql_db_select("phprockers", $con) or mysql_error();
?>
<form method="POST" action="" enctype="multipart/form-data">

    Images 1: <input type=file name='images1' ><br>
    Images 2: <input type=file name='images2' ><br>
    Images 3: <input type=file name='images3' ><br>
    <input type="submit" name="submit" value="Submit" />

</form>

Important functions in Wordpres

0 comments
 Wordpress Functions:
================
get_the_excerpt() -  It can be used to get the post excerpt content in the current post.

get_post($post->ID) - It can be used to get the post details about current post. It has title,categoryid, category name, post status etc. Here post->ID is optional.

get_the_post_thumbnail($page->ID,array(150,200),'thumbnail') - It can be used for retrive the thumbnail image for the post.

the_title() - It can be used for retrive the title for current post.

Limitatin in MYSQL

0 comments
Table attribute names are eliminated after 31 characters in the database.

The maximum character of database and table is 122 characters in the mysql.

The maximum number of table in a mysql database is 1792.

The maximum number of database in mysql is 20320.

The maximum number of attributes (that is, columns and indexes) per table is 128 characters.

The maximum number of attributes per key is 32.

The maximum permitted size of one row in table is 8052 bytes.

Get the second highest salary from employee table in mysql

2 comments

We have get the second, third, fourth etc. hightest salary from the employee table very easily in mysql/sql.

Getting max highest salary:
===================

SELECT max(salary) as salary FROM employee;

Getting N th highest salary syntax:
========================

SELECT salary FROM employee as emp WHERE (n-1) = (SELECT count(*) FROM employee as emp2 WHERE emp2.salary > emp.salary)

Getting 2nd maximum salary:
=====================
Above syntax, subsitute n=2, then we have to get second max salary.

SELECT salary FROM employee as emp WHERE (2-1) = (SELECT count(*) FROM employee as emp2 WHERE emp2.salary > emp.salary)

mysql_escape_string in php

0 comments
This function escacpe the single quotes, double quotes and unwanted symbol from our passing strings.

Format :
========
mysql_escape_string(string_name);

Example:
======
$first_name = mysql_escape_string($first_name);


Keep in mind:
=============
mysql_escape_string() cann't escape the % and _.

List out all the mysql database name in php

0 comments
List out all the mysql database name using follwing php code.

<?php

    error_reporting(E_ALL);

    $connection = mysql_connect('localhost', 'root', '');

    $database_list = mysql_list_dbs($connection);

    $count = mysql_num_rows($database_list);

    for($i=0;$i<$count;$i++) {

        echo mysql_db_name($db_list, $i) . "<br/>";
    }

?>

How to get the mysql last inserted id using PHP?

1 comments
We have to easily get the last inserted id in mysql table using below code.

<?php

$connection = mysql_connect('localhost', 'MYSQL_USERNAME', 'MYSQL_PASSWORD') or mysql_error();

mysql_select_db('DATABASE_NAME', $connection)  or mysql_error();

$query = "INSERT INTO emp_table (emp_id, emp_name, emp_qualification, emp_salary) VALUES ('SC70699', 'Ramakrishnan', 'MCA', '13186')";

mysql_query($query );

$last_insert_id = mysql_insert_id();

echo "Last insert id in employee table: ".$last_insert_id;

mysql_close($connection) ;

?>

How to get the post tags for current post/page?

0 comments
We can easily get the post tags for current post using following code and give the link for each post tags.

<?php
$current_post_tags = wp_get_post_tags($post->ID);
$post_tags_link .= '<ul class="post-tags-link">';
for($i=0; $i < count($current_post_tags ); $i++) {
$post_tags_link .= '<li><a href ="'.get_bloginfo('url').'/'.$current_post_tags[$i]->slug.'">'.$current_post_tags[$i]->name.'</a></li>';           

$post_tags_link .= '</ul>';
//echo "<pre>";print_r($current_post_tags);
?>
Find more about:<?php echo $post_tags_link; ?>

Breadcrumbs in wordpress

0 comments
global $wp_query;
$Post_ID = $wp_query->post->ID;   
$category = get_the_category();
if(!empty($category)) {
    $current_category = $category[0];
    $parent_category = $current_category->category_parent;
    $bread_cat_link .= '<ul class="post-categories">';
    if ( $parent_category != 0 ) {
    $bread_cat_link .= '<li><a href="' . get_category_link($parent_category) . '">' . get_cat_name($parent_category) . '</a></li><span>&gt;</span>';

How to get the next and Previous title link for current post in wordpress?

0 comments
<div id="posts_navigation">
    //get the previous link for current page
    <?php if(get_adjacent_post(true, '', false)) { ?>
    <div class="next"><?php next_post_link('%link', '%title', TRUE, '');?></div>
    <span> | </span>
    <?php } ?>
    //get the next link for current page
    <?php if(get_adjacent_post(true, '', true)) { ?>
    <div class="prev"><?php previous_post_link('%link', '%title', TRUE, '');?></div>
    <?php } ?>
</div>

Next and Previous link for current post in wordpress

0 comments
<div id="posts_navigation">
    //get the previous link for current page
    <?php if(get_adjacent_post(true, '', false)) { ?>
    <div class="next"><?php next_post_link('%link', '&lt; Previous', TRUE, '');?></div>
    <span> | </span>
    <?php } ?>
    //get the next link for current page
    <?php if(get_adjacent_post(true, '', true)) { ?>
    <div class="prev"><?php previous_post_link('%link', 'Next &gt;', TRUE, '');?></div>
    <?php } ?>
</div>

How to get the custom field values in wordpress?

0 comments
First we should know, what are the custom fileds values are available now. get_post_custom_keys() can be used to find all the custom fields in current post.

<?php
$get_list_custom_fileds = get_post_custom_keys();
print_r($get_list_custom_fileds);
?>

Then we have to esily get the particular custom field value for current post. Here the example of get the book author name for current post.

How do submit a form without submit button?

0 comments
Easily submit the values without submit button using javascript in the form.  You can use following code in your program.

<script type="javascript/text">
document.formname.submit();
</script>

Get nav menu locations in wordpress

0 comments
Definition of get_nav_menu_locations():

It is returns an array with the registered navigation menu locations and which menu is assigned to it.
$locations = get_nav_menu_locations();
echo "<pre>";
print_r($locations);
echo "</pre>";

How to get the register menu items from "Theme Locations"?

0 comments
Very simple to get the register menu items,

$locations = get_nav_menu_locations();

Returns an array with the registered navigation menu locations and which menus are assigned to it.

$args = array(
        'order'                     => 'ASC',
        'orderby'                 => 'menu_order',
        'post_type'              => 'nav_menu_item',
        'post_status'            => 'publish',
        'output_key'            => 'menu_order',
        'nopaging'               => true,
        'depth'                    => '0',
        'update_post_term_cache' => false
    );

How to register the menu in "Theme Location"?

0 comments
In wordpress, very easy to register the menu in "Theme Location". For that so you have to follow some steps.

Step 1: Goto localhost/WORDPRESS FOLDER/wp_content/themes/twentyeleven/

Step 2: Open functions.php file.

Step 3: "register_nav_menu( 'primary', __( 'Primary Menu', 'twentyeleven' ) );" find this inside the file. After find the code, below you have to write a  following code.

Where is the "Theme Location" presents in wordpress?

0 comments
Go to admin panel in wordpress.

See left sidebar,Go to "Appearance" then click the "Menus".

At first time no menus are available in wordpress. After creating the menu, then only visible "Theme Location" to us.

How to get the menu items in wordpress?

0 comments
Using wp_get_nav_menu_items() function, we can get all the items(post,page,category) in the menu.

<?php
    $menu_items = wp_get_nav_menu_items('64');
    $menu_list = '<div class="menu_list">';
    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title = $menu_item->title;
        $url = $menu_item->url;
        $menu_list .= '<div><a href="' . $url . '">' . $title . '</a></div>';
    }
    $menu_list .= '</div>';
    echo $menu_list;
?>

Cron Job in ubuntu

0 comments
Cron Job in PHP
============
If we put the file in cron, It will run automatically by setting the time limit. Using time limit we have run the file every min/hour/day/month etc.

dckap1@dckap-desktop:~$ sudo su

[sudo] password for dckap1: **************
root@dckap-desktop:/home/dckap1# crontab -e

If you are using the cron in first time, First you should select the editor. It(crontab -e) will show five editor. Then you have to select the editor. Here nano editor is very useful in this, so you should select the nano editor.


Pagination in php

0 comments
When we have a large list of items, we can display them grouped in pages and presents navigational elements to move from one page to another. This code creates a pagination for listing the page per 10 records.

<?php

$con = mysql_connect('localhost','ramakrishnan','raman') or die(mysql_error()); ;
mysql_select_db('rama_db',$con) or die(mysql_error()); ;

$page = $_REQUEST['page'];
if($page == "" || $page == null ) {
    $page = 1;
} else {
    $page = $page;
}

//setting the limit for fetching the records.
$per_page_limit = 10;
if($page >1) {
    $start_limit = ($page-1)*$per_page_limit;
    } else {
    $start_limit = 0;
}

How to write a query in Joomla

0 comments
If we want to execute the query in joomla, We have to follow some basic steps in Joomla. Then only query will execute,

<?php

       $db =& JFactory::getDBO();
       $query = "SELECT * FROM Joomla_tables";
       $db->setQuery($query);
       $result = $db->query();
       echo "<pre>";
       print_r($result);
       echo "</pre>";

?>

Static method in php

0 comments
1. Using "static" keyword to declare the static methods.

2. We can access the static methods without creating an instantiation(object) of the class.

Difference between abstract class and interface in php

1 comments

S.No

Abstract Class

Interface Class

1
Abstract class - method must be declared as abstract. Abstract methods doesn’t have any definition. The sub class (extend class) can have the definition for those abstract method. Interface - all the methods by default are abstract methods only. So one cannot declare variables in interfaces. The sub class (implement class) can have all method definition for those methods.

2
The Abstract methods can declare with Access modifiers like public, internal, protected. All methods declared in an interface must be public.

3
Abstract class can contain variables and concrete methods. Interfaces cannot contain variables and concrete methods, but we can possible to define the constants.

4
An abstract class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class. A class can implement many interfaces and Multiple interface inheritance is possible.

Get current custom post type in wordpress

0 comments
We can get easily custom post type or normal post type in wordpress by using the post id.
global $posts;
$post_id = $posts->ID;
$post_type = get_post_type($post_id);
echo $post_type;

Get current post id in wordpress

0 comments
2 ways, we have to get current post id in wordpress
First way: 
global $posts;
$current_post_id = $posts->ID;
Second way:  

global $wp_query;
$current_post_id = $wp_query->post->ID;

Get Category Name from Post ID in WordPress

0 comments
Get the category name by using the post id in wordpress,
Step 1: First we have to get the post id
global $posts;
$post_id = $posts->ID;

Step 2: After the get the post id, then we get the category is very simple.
$category = get_the_category($postID);

$category_name = $category->cat_name