Tuesday, February 26, 2013

XML AND JOSN DIFFER

http://stereolambda.com/2010/03/19/why-is-json-so-popular-developers-want-out-of-the-syntax-business/

Without wanting to dispute the relative merits of JSON (which I know very little about) and XML, I would say that XML is extremely good for automatic treatment, information exchanges between different applications, and similar—but is simply not constructed for intense user/developer interaction.
The fact that it is human readable and editable is a clear bonus, but can mislead people to think that it is something they should work directly with. XML, IMO, belongs further down the abstraction hierarchy where it rarely encounters any human. (Obviously, library developers and the like will eventually have to deal directly with it.)
A very obvious parallel is HTML: When I am allowed to choose (not always the case) webdevelopment directly in HTML is the exception and most HTML is generated through other types of document descriptions, say a basic markup language (as known from e.g. Wikipedia) or through JSP-style tag libraries. (This comment should not in anyway be seen as a recommendation of WYSIWYG HTML-editors—that is a very different topic.)

WHAT DOES SOAP,XML,JSON

JSON is a standard to represent human-readable data. It merely represents data, nothing more.
SOAP is a protocol specification for transmiting information and calling web services, and uses XML to encode it. SOAP works over HTTP (amogst other network protocols).
XML-RPC is another protocol, used for transmiting information and calling remote procedures. It doesn't run over HTTP, but is rather a different protocol, different port, etc.
So the main difference between SOAP and XML-RPC that the former wraps inside HTTP, while the latter does not. JSON is something completely different.

Monday, February 25, 2013

mysql full text search example

Blind query expansion (also known as automatic relevance feedback) is enabled by adding WITH QUERY EXPANSION following the search phrase. It works by performing the search twice, where the search phrase for the second search is the original search phrase concatenated with the few most highly relevant documents from the first search. Thus, if one of these documents contains the word databases and the word MySQL, the second search finds the documents that contain the word MySQL even if they do not contain the word database. The following example shows this difference:
mysql> SELECT * FROM articles
    -> WHERE MATCH (title,body) AGAINST ('database');
+----+-------------------+------------------------------------------+
| id | title             | body                                     |
+----+-------------------+------------------------------------------+
|  5 | MySQL vs. YourSQL | In the following database comparison ... |
|  1 | MySQL Tutorial    | DBMS stands for DataBase ...             |
+----+-------------------+------------------------------------------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM articles
    -> WHERE MATCH (title,body)
    -> AGAINST ('database' WITH QUERY EXPANSION);
+----+-------------------+------------------------------------------+
| id | title             | body                                     |
+----+-------------------+------------------------------------------+
|  1 | MySQL Tutorial    | DBMS stands for DataBase ...             |
|  5 | MySQL vs. YourSQL | In the following database comparison ... |
|  3 | Optimizing MySQL  | In this tutorial we will show ...        |

Saturday, February 23, 2013

how to trim a string using javascript

Many modern browsers (such as Firefox 3, Opera 11, Safari 5.x, Chrome 10, Internet Explorer 9 in standards mode) support the string.trim() method, which allows you to rewrite the above much shorter:

str = str.trim()

For browsers that do not support string.trim(), e.g. Internet Explorer 8 or earlier, you can add your own trim() method to string object's prototype by including the following script in the <HEAD> section of your page, prior to any script that uses string.trim():

if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');
 }
}

   

Friday, February 22, 2013

add forign key in mysql alter table

CREATE TABLE IF NOT EXISTS `parent` (
  `id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE IF NOT EXISTS `child` (
  `id` int(11) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  KEY `par_ind` (`parent_id`),
  KEY `child_to_module_fk_company` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `child`
  ADD CONSTRAINT `company_to_module_fk_company` 
    FOREIGN KEY (`parent_id`)
    REFERENCES `parent` (`id`)
    ON DELETE RESTRICT
    ON UPDATE RESTRICT;

Thursday, February 21, 2013

jquery interview questions and answers

1) What is jQuery Selectors? Give some examples.

  • jQuery Selectors are used to select one or a group of HTML elements from your web page.
  • jQuery support all the CSS selectors as well as many additional custom selectors.
  • jQuery selectors always start with dollar sign and parentheses: $()
  • There are three building blocks to select the elements in a web document.
1) Select elements by tag name
Example: $(div)
It will select all the div elements in the document.
2) Select elements by ID
Example: $(#xyzid”)
It will select single element that has an ID of xyzid
3) Select elements by class
Example: $(“.xyzclass”)
It will select all the elements having class xyzclass

2) How can we give face effect in jQuery?

  • In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo
  • This methods change the opacity of element with animation.
Syntax:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
  • “speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “opacity” specify the value that allows the fading to given opacity.
  • “callback” is the function which we want to run once the fading effect is complete.
For example
$("clickme").click(function(){
$("mydiv").fadeTo("slow",0.50);
});

$("clickme").click(function(){
$("mydiv").fadeOut(3000);
});.

3) Explain the animate function.

-The animate function is used to apply the custom animation effect to elements.
-Syntax:
$(selector).animate({params}, [duration], [easing], [callback])
  • “param” defines the CSS properties on which you want to apply the animation.
  • “duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation effect is complete.
For example
<div id="clickToAnimate">
Click Me
</div>
<div id="mydiv" style=”width:200px; height:300px; position: relative; right: 20px;">
</div>

Following is the jQuery to animate opacity, left offset, and height of the mydiv element

$('# clickToAnimate’).click(function() {
$('#book').animate({
opacity: 0.30,
left: '+=20',
height: 'toggle'
}, 3000, function() {
// run after the animation complete.
});
});

4) What is .siblings() method in jQuery?

  • When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method.
  • We filter the elements fetched by an optional selector.
  • Syntax : .siblings( [selector])
  • “selector” is the selector expression which specify the matched elements.
For example
<ul>
<li> item 1 </li>
<li id=”second_item”> item 2 </li>
<li class=”myitem”> item 3 </li>
<li class=”myitem”> item 4 </li>
</ul>
Now we want to find the siblings of the element of id “second_item” and change the text color to Blue :
$(‘li.second_item’).siblings().css(‘color’,’blue’);
If we want specific sibling elements for example the elements having class “myitem” then we can pass a optional selector:
$(‘li.second_item’).siblings(‘.myitem’).css(‘color’,’blue’);

5) Explain width() vs css(‘width’).

  • In jQuery, there are two way to change the width of an element.
  • One way is using .css(‘width’) and other way is using .width().
For example
$(‘#mydiv’).css(‘width’,’300px’);
$(‘#mydiv’).width(100);
  • The difference in .css(‘width’) and .width() is the data type of value we specify or return from the both functions.
  • In .css(‘width’) we have to add “px” in the width value while in .width() we don’t have to add.
  • When you want to get the width of “mydiv” element then .css(‘width’) will return ‘300px’ while .width() will return only integer value 300.

6) What is the use of jQuery.data()?

  • jQuery.data() is used to set/return arbitrary data to/from an element.
  • Syntax: jQuery.data(element, key, value)
  • “element” is the DOM element to which the data is associated.
  • “key” is an arbitrary name of the piece of data.
  • “value” is value of the specified key.
  • Suppose we want to set the data for a span element:
jQuery.data(span, “item”, { val1: 10, val2: "myitem" });
If we want to retrieve the data related to div element and set it to label’s data:
$("label:val1").text(jQuery.data(div, "item").val1);
$("label:val2").text(jQuery.data(div, "item").val2);

7) Explain bind() vs live() vs delegate() methods.

-The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also.
-The difference between live() and delegate() methods is live() function will not work in chaining. It will work only on an selector or an element while delegate() method can work in chaining.
For example
$(document).ready(function(){
$("#myTable").find("tr").live("click",function(){
alert($(this).text());
});
});

Above code will not work using live() method. But using delegate() method we can accomplish this.
$(document).ready(function(){
$("#dvContainer")children("table").delegate("tr","click",function(){
alert($(this).text());
});
});

8) Explain the each() function.

-The each() function specify the function to be called for every matched element.
Syntax:
$(selector).each(function (index, element))
  • “index” is the index position of the selector.
  • “selector” specifies the current selector where we can use “this” selector also.
  • In the case when we need to stop the each loop early then we can use “return false;”
For example
$("#clickme").click(function(){
$("li").each(function(){
document.write($(this).text())
});
});
This will write the text for each “li” element.

9) Explain slideToggle() effect.

-slideToggle() effect is used to give animated sliding effect to an element.

Syntax:
slideToggle([ duration] [, easing] [, callback])
  • “duration” is the number specifying how long the animation will run.
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation is complete.
  • If the element is visible then this effect will slide the element up side and make it completely hidden. If the element is hidden then slideToggle() effect will slide it down side and make it visible.
  • We can specify the toggle speed with this effect.
For example
$("#clickme").click(function(){
$("#mydiv").slideToggle(“slow”, function(){
//run after the animation is complete.
});
});

10) What is difference between $(this) and ‘this’ in jQuery?

Refer the following example
$(document).ready(function(){
$(‘#clickme’).click(function(){
alert($(this).text());
alert(this.innerText);
});
});
-this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery.
-In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element.

11) What is the use of param() method.

  • The param() method is used to represent an array or an object in serialize manner.
  • While making an ajax request we can use these serialize values in the query strings of URL.
  • Syntax: $.param(object | array, boolValue)
  • “object | array” specifies an array or an object to be serialized.
  • “boolValue” specifies whether to use the traditional style of param serialization or not.
For example:
personObj=new Object();
empObject.name="Arpit";
empObject.age="24";
empObject.dept=”IT”;
$("#clickme").click(function(){
$("span").text($.param(empObject));
});
It will set the text of span to “name=Arpit&age=24&dep=IT”

12) What is jQuery.holdReady() function?

-By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
-This method should be call before we run ready event.
-To delay the ready event, we have to call
jQuery.holdReady(true);
-When we want to release the ready event then we have to call
jQuery.holdReady(false);
-This function is helpful when we want to load any jQuery plugins before the execution of ready event.
For example
$.holdReady(true);
$.getScript("xyzplugin.js", function() {
$.holdReady(false);
});

13) Explain .empty() vs .remove() vs .detach().

-.empty() method is used to remove all the child elements from matched elements.
-.remove() method is used to remove all the matched element. This method will remove all the jQuery data associated with the matched element.
-.detach() method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements.
-.remove() is faster than .empty() or .detach() method.
Syntax:
$(selector).empty();
$(selector).remove();
$(selector).detach();

14) How to read, write and delete cookies in jQuery?

-To deal with cookies in jQuery we have to use the Dough cookie plugin.
-Dough is easy to use and having powerful features.
-Create cookie
$.dough("cookie_name", "cookie_value");
Read Cookie
$.dough("cookie_name");
Delete cookie
$.dough("cookie_name", "remove");

15) Is window.onload is different from document.ready()?

- The window.onload() is Java script function and document.ready() is jQuery event which are called when page is loaded.
- The difference is that document.ready() is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
- Suppose there is very large image on a page, at that time window.onload() will wait until that image is loaded totally.
- So while using the window.onlaod() function the execution will be slow, but the document.ready() will not wait until the image is loaded.

16) What is Chaining in jQuery?

- Chaining is very powerful feature of jQuery.
- Chaining means specifying multiple function and/or selectors to an element.
- Examine the below example
$(document).ready(function(){
$('#mydiv').css('color', 'blue');
$('#mydiv').addClass('myclass');
$('#mydiv').fadeIn('fast');
}
By using chaining we can write above code as follows
$(document).ready(function(){
$('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast');
});
-Advantage of chaining is that it makes your code simple and simple to manage.
-The execution becomes faster because the code search for the element only once.

17) What is difference between sorting string array and sorting numerical array in jQuery?

The sort method is used to sort any array elements. It sorts the string elements alphabetically.
For example
$(document).ready(function(){
var mylist = [ “Apple”,”Orange”,”Banana”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});
It will give following output
Apple
Banana
Orange
Now we declare a numerical array and use sort() method to sort its elements.
$(document).ready(function(){
var mylist = [ “20”,”3””100”,”50”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});
It will give following output
100
20
3
50

18) What is difference between prop and attr?

  • In jQuery both prop() and attr() function is used to set/get the value of specified property of an element.
  • The difference in both the function is that attr() returns the default value of the property while the prop() returns the current value of the property.
For example
<input value="My Value" type="text"/>

$('input').prop('value', 'Changed Value');

-.attr('value') will return 'My Value'
-.prop('value') will return 'Changed Value'

19) How to always reference latest version of jQuery?

When you reference the jQuery on your web page, you have to specify the version number also.
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>
</script>
Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released.
To achieve this you have to use following code
<script type=”text/javascript”
src=”http://code.jquery.com/jquery-latest.min.js”>
</script>
This code will always reference the latest version of jQuery in your page.

20) What is resize() function in jQuery?

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).
Syntax:
.resize([event_data], handler(event_object))
-The “event_data” is the data to be sent to the handler.
-The “handler(event_object)” is a function to be called each time when the window is resized.
For example
$(window).resize(function() {
$('#message).text('window is resized to ' + $(window).width() + ‘x’ + $(window).height());

What is meant by Object Oriented Programming

1) What is meant by Object Oriented Programming?
     OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.


2) What is a Class?
     Class is a template for a set of objects that share a common structure and a common behaviour.

3) What is an Object?
     Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

4) What is an Instance?
     An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

5) What are the core OOP’s concepts?
     Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.

6) What is meant by abstraction?
     Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation?
     Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

8) What is meant by Inheritance?
     Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

9) What is meant by Polymorphism?
     Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

10) What is an Abstract Class?
     Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.


11) What is an Interface?
     Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.

12) What is a base class?
     Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

13) What is a subclass?
     Subclass is a class that inherits from one or more classes

14) What is a superclass?
     superclass is a class from which another class inherits.

15) What is a constructor?
     Constructor is an operation that creates an object and/or initialises its state.

16) What is a destructor?
     Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.

17) What is meant by Binding?
     Binding denotes association of a name with a class.

18) What is meant by static binding?
     Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

19) What is meant by Dynamic binding?
     Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

20) Define Modularity?
     Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.


21) What is meant by Persistence?
     Persistence is the property of an object by which its existence transcends space and time.

22) What is colloboration?
     Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.

23) In Java, How to make an object completely encapsulated?
     All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

24) How is polymorphism acheived in java?
     Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.

Monday, February 18, 2013

sort an array without using array php

<?php
function sort1($arr) {
  for ($i=0; $i<count($arr); $i++) {
    for ($j=0; $j<count($arr)-1-$i; $j++) {
        if ($arr[$j+1] <$arr[$j]) {
            swap($arr, $j, $j+1);
        }
     }
  }
  return $arr;
}

function swap(&$arr, $a, $b) {
   $tmp = $arr[$a];
   $arr[$a] = $arr[$b];
   $arr[$b] = $tmp;
}

//using sorting functions
$arr = array(1,13,2,9,5,7,0,3);

 echo("Before sorting");
 print_r($arr);



 echo("qafter sorting array");
 print_r(sort1($arr));

php session handling class

<?php
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers


session_start();
$handler->open('D:\xampp\tmp\bikas','bikash');
$sessionid=session_id();
$data=array(
'bikash',
'delhi');

$handler->write($sessionid,$data);
$handler->read($sessionid);
$handler->destroy($sessionid);
$handler->close();

how to insert image blob and read blob mysql image using php

<?php
   if (isset($_FILES['img']) && $_FILES['img']['size'] > 0) {

      // Temporary file name stored on the server
       $tmpName  = $_FILES['img']['tmp_name']; 
       $exttype=$_FILES['image']['type'];
       $sizen=$_FILES['img']['size'];
   
      // Read the file
      $fp      = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      $data = $data;
      fclose($fp);
     
      /*insert into mysql query after that select and show*/
     $ext = explode('/', $image_type);
     $name = 'colors';

header("Content-Type: image/gif");
echo $data;    
exit;
     
}
else {?>
  <form name="f" method="post" action="test.php" enctype="multipart/form-data">
<input type="file" name="img"  />
<input type="submit" name="test" value="imagup" />
</form>

<?php
}

?>

how to get keyboard ascii value using javascript

 how to submit form when enter key press


<script language="javascript">
function whichKey(evt) {
    if(evt.keyCode==13){
    document.f.submit();
    }
}
</script>
<form name="f" method="get" action="test1.php">
<input type="text" name="tt" onkeypress="whichKey(event);">
</form>

easy way to create wordpress plugin

In this tutorial you will learn how to create a wordpress plugin from scratch.

Prerequisites:
  • Wordpress installed on your server
  • Basic knowledge of wordpress
Aim:
After this tutorial you will learn
  • How to create a wordpress plugin
  • How to create a Admin menu
  • How to show data from database in the admin
  • How to install & uninstall your tables dynamically
  • How to show data from database in the front end
Remember our aim is not making any useful plugin. Our aim is to teach you how to make a plugin only. A complete small plugin that have most of the features.

So lets start.

Wordpress keeps it plugins at wp-content/plugins/ folder. So whatever we will do is under this folder.
Step 1: Create plugin Create a folder pro-questions inside wp-content/plugins/
Create a file pro-questions.php inside the folder pro-questions. You can give your folder/file name as your needs. We chose pro-questions. So this is our working directory.
Now open the file pro-questions.php and put some information regarding your plugin. Remember wordpress will recognize you by this information.
1
2
3
4
5
6
7
8
/*
Plugin Name: Plugin Tutorial
Plugin URI: http://www.pro-questions.com
Description: Wordpress plugin tutorial
Author: Pro Question
Version: 1.0.1
Author URI: http://pro-questions.com
*/
Now go to the admin and click Plugins. You will see your plugin is in the listing.
Step 2: Create tables dynamically Lets define some constants for your site. This will help you in future.
1
2
3
4
5
6
7
8
9
10
$siteurl = get_option('siteurl');
define('PRO_FOLDER', dirname(plugin_basename(__FILE__)));
define('PRO_URL', $siteurl.'/wp-content/plugins/' . PRO_FOLDER);
define('PRO_FILE_PATH', dirname(__FILE__));
define('PRO_DIR_NAME', basename(PRO_FILE_PATH));
// this is the table prefix
global $wpdb;
$pro_table_prefix=$wpdb->prefix.'pro_';
define('PRO_TABLE_PREFIX', $pro_table_prefix);
you defined some constants specific to your folder and a different prefix for your tables. By this you will organize and recognize your tables better. This also prevents naming mismatch.
Now you need some tables of your needs which will created dynamically at time of plugin activation. And also dropped at being deactivated. Lets do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
register_activation_hook(__FILE__,'pro_install');
register_deactivation_hook(__FILE__ , 'pro_uninstall' );

function pro_install()
{
    global $wpdb;
    $table = PRO_TABLE_PREFIX."tutorial";
    $structure = "CREATE TABLE $table (
        id INT(9) NOT NULL AUTO_INCREMENT,
        name VARCHAR(80) NOT NULL,
        website VARCHAR(20) NOT NULL,
        description text,
 UNIQUE KEY id (id)
    );";
    $wpdb->query($structure);
   // Populate table
    $wpdb->query("INSERT INTO $table(name, website, description)
        VALUES('Pro Questions', 'pro-questions.com','This Is A Programming 
Questions Site')");
}
function pro_uninstall()
{
    global $wpdb;
    $table = PRO_TABLE_PREFIX."tutorial";
    $structure = "drop table if exists $table";
    $wpdb->query($structure);  
}
register_activation_hook(__FILE__,'pro_install')
this function run the pro_install() function at time of plugin activation. As your function is in the
same file just give __FILE__ in the first argument, otherwise give relative path to the file.
register_deactivation_hook(__FILE__ , 'pro_uninstall')
this function run the pro_uninstall() function at time of plugin deactivation.
pro_install() & pro_uninstall() function will do the rest for you. Don’t forget to give the global keyword
 before $wpdb;
Now go to the Admin and click the ‘Activate’ link below your plugin name. Go to the phpmyadmin and
you will see your table is ready. Now click ‘Deactivate’ link and see your table is not there.
Step 3: Create menu for Admin Activate the plugin again.
Now you need admin control to do something. So first create a menu for your plugin.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
add_action('admin_menu','pro_admin_menu');

function pro_admin_menu() { 
 add_menu_page(
  "Plugin tutorial",
  "Plugin tutorial",
  8,
  __FILE__,
  "pro_admin_menu_list",
  PRO_URL."/images/menu.gif"
 ); 
 add_submenu_page(__FILE__,'Site list','Site list','8','list-site',
'pro_admin_list_site');
}
Now look the admin site. You will found a seperate menu for your plugin. Click the menu and see
 what happens. you will see some errors because the functions are missing.
add_action('admin_menu','pro_admin_menu')
this will call the pro_admin_menu() function at the admin site.
pro_admin_menu()
creates a menu in the admin. Call the function pro_admin_menu_list() on clicking the menu. I have
given a image menu.gif for my menu.
add_submenu_page(__FILE__,'Site list','Site list','8','list-site','pro_admin_list_site')
this will create a submenu for you where list-site is the page name and pro_admin_list_site is the
 function name called on clicking it.
Step 4: Display data in Admin Now we will create the pro_admin_menu_list() & pro_admin_list_site() functions. Now add the functions as below.
1
2
3
4
5
6
7
8
9
10
function pro_admin_menu_list()
{
 echo "Now i know how to create a plugin in wordpress!";
}
// function for the site listing
function pro_admin_list_site()
{
  include 'admin-list-site.php';
}
create a file admin-list-site.php inside the pro-questions folder and add the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div class="wrap">  
 <?php    echo "<h2>" . __( 'Site Listing' ) . "</h2>"; ?>  
<table class="widefat page fixed" cellspacing="0">
  <tbody>
<?php
global $wpdb;
$sql = "SELECT *FROM ".PRO_TABLE_PREFIX."tutorial where  1";
$results = $wpdb->get_results($sql);
if(count($results) > 0)
{
 foreach($results as $result)
 {
 echo "<tr>
 <td>".$result-> name."</td><td>".$result->website."</td>
<td>".$result->description."</td>
 </tr>";
 }    
}
?>
  </tbody>
</table>
 </div>
now click the Site list submenu and see what you have done. The data from your tables are there.
pro_admin_menu_list()
this function simply adds some text. You can do whatever you wish.
pro_admin_list_site()
this function simply adds admin-list-site.php file. admin-list-site.php did the necessary work to for you.
Step 5: Create table header like wordpress Now if you want to give some wordpress like table heading then just modify the admin-list-site.php file as below
1
2
3
4
5
6
7
8
9
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
// 'admin-list-site.php’ file 
<?php
$columns = array(
  'name' => 'Name',
  'website' => 'Website',  
  'description' => 'Description'
 );
 register_column_headers('pro-list-site', $columns); 
?>
<div class="wrap">  
 <?php    echo "<h2>" . __( 'Site Listing' ) . "</h2>"; ?>  
<table class="widefat page fixed" cellspacing="0">
  <thead>
  <tr>
<?php print_column_headers('pro-list-site'); ?>
  </tr>
  </thead>

  <tfoot>
  <tr>
<?php print_column_headers('pro-list-site', false); ?>
  </tr>
  </tfoot>
  <tbody>
<?php
global $wpdb;
$sql = "SELECT *FROM ".PRO_TABLE_PREFIX."tutorial where  1";
$results = $wpdb->get_results($sql);
if(count($results) > 0)
{
 foreach($results as $result)
 {
 echo "<tr>
 <td>".$result-> name."</td><td>".$result->website."</td>
<td>".$result->description."</td>
 </tr>";
 }    
}
?>
  </tbody>
</table>
 </div>

Click the Site list menu again and see the difference.
you have registered a header named pro-list-site with register_column_headers() function and called it
with print_column_headers() function
Your admin portion is complete now.
Now you have to show the same in the front-end to complete the project.
So lets start.
Step 6: Display data in front end Create a post and put in the content the code [pro_tutorial_site_listing]. Don’t forget to give the braces.
Now see the post in the frontend. You will found the text.
Next go to the pro-questions.php file and add some code
1
2
3
4
5
6
//Add ShortCode for "front end listing"
add_shortcode("pro_tutorial_site_listing","pro_tutorial_site_listing_shortcode")
;
 function pro_tutorial_site_listing_shortcode($atts) 
{ 
   include 'admin-list-site.php';
}
now see the post you just created. It’s content is changed.
add_shortcode("pro_tutorial_site_listing","pro_tutorial_site_listing_shortcode")
this function search the [pro_tutorial_site_listing] text in post and called  
pro_tutorial_site_listing_shortcode()
 function if found. Remember the code must be unique. That’s why it is a better idea to add a prefi
x( pro for example ) before it.
I have just included the admin-list-site.php file for example. You can include a file of your needs.
That’s all. Hurray!
Area of improvement:
  • Create Add, Edit, Delete for you data
  • Change the look at the front end
I hope you can do this now. 

Sunday, February 17, 2013

what is main difference between javascript and jquery

JavaScript is a language. jQuery is a framework built with JavaScript to help JavaScript programmers who are doing common web tasks.

ajax flow and easy step

his section will give you clear picture of the exact steps of AJAX operation.

Steps of AJAX Operation

  1. A client event occurs
  2. An XMLHttpRequest object is created
  3. The XMLHttpRequest object is configured
  4. The XMLHttpRequest object makes an asynchronous request to the Webserver.
  5. Webserver returns the result containing XML document.
  6. The XMLHttpRequest object calls the callback() function and processes the result.
  7. The HTML DOM is updated
Lets take these steps one by one

1. A client event occurs

  • A JavaScript function is called as the result of an event
  • Example: validateUserId() JavaScript function is mapped as a event handler to a onkeyup event on input form field whose id is set to "userid"
  • <input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();">

2. The XMLHttpRequest object is created

var ajaxRequest;  // The variable that makes Ajax possible!
function ajaxFunction(){
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
}

3. The XMLHttpRequest object is Configured

In this step we will write a function which will be triggered by the client event and a callback function processRequest() will be registered
function validateUserId() {
   ajaxFunction();
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);
}

4. Making Asynchornous Request to the Webserver

Source code is available in the above piece of code. Code written in blue color is responsible to make a request to the web server. This is all being done using XMLHttpRequest object ajaxRequest
function validateUserId() {
   ajaxFunction();
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatechange = processRequest;

   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   ajaxRequest.open("GET", url, true);
   ajaxRequest.send(null);

}
Assume if you enter mohammad in userid box then in the above request URL is set to validate?id=mohammad

5. Webserver returns the result containing XML document

You can implement your server side script in any language. But logic should be as follows
  • Get a request from the client
  • Parse the input from the client
  • Do required processing.
  • Send the output to the client.
If we assume that you are going to write a servlet then here is the piece of code
public void doGet(HttpServletRequest request, 
                    HttpServletResponse response)
                        throws IOException, ServletException 
{
   String targetId = request.getParameter("id");

   if ((targetId != null) && 
       !accounts.containsKey(targetId.trim())) 
   {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("true");
   } 
   else 
   {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("false");
   }
}

6. Callback function processRequest() is called

The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will recieve the result from the server and will do required processing. As in the following example it sets a variable message on true or false based on retruned value from the Webserver.
function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}

7. The HTML DOM is updated

This is the final step and in this step your HTML page will be updated. It happens in the following way
    JavaScript technology gets a reference to any element in a page using DOM API
  • The recommended way to gain a reference to an element is to call.
document.getElementById("userIdMessage"), 
// where "userIdMessage" is the ID attribute 
// of an element appearing in the HTML document

  • JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements. Here is the example
<script type="text/javascript">
<!--
 function setMessageUsingDOM(message) {
    var userMessageElement = 
           document.getElementById("userIdMessage");
    var messageText;
    if (message == "false") {
       userMessageElement.style.color = "red";
       messageText = "Invalid User Id";
    } else {
       userMessageElement.style.color = "green";
       messageText = "Valid User Id";
    }
    var messageBody = document.createTextNode(messageText);


    // if the messageBody element has been created simple 
    // replace it otherwise append the new element

    if (userMessageElement.childNodes[0]) {
       userMessageElement.replaceChild(messageBody,
       userMessageElement.childNodes[0]);
    } else {
       userMessageElement.appendChild(messageBody);
    }
}
-->
</script>
<body>
<div id="userIdMessage"><div>
</body>

ajax explanation details and asychronious

ans-AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

AJAX applications are browser- and platform-independent!

All modern browsers support the XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject


To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

    * A cached file is not an option (update a file or database on the server)
    * Sending a large amount of data to the server (POST has no size limitations)
    * Sending user input (which can contain unknown characters), POST is more robust and secure than GET

If you want to send information with the GET method, add the information to the URL:


xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();


To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");


setRequestHeader(header,value) ->Adds HTTP headers to the request.

header: specifies the header name
value: specifies the header value


AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true:

xmlhttp.open("GET","ajax_test.asp",true);

Sending asynchronously requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.

With AJAX, the JavaScript does not have to wait for the server response, but can instead:

    * execute other scripts while waiting for server response
    * deal with the response when the response ready


Async=true

When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Async=false

To use async=false, change the third parameter in the open() method to false:

Using async=false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement:

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

The onreadystatechange event
-------------------------------

When a request to a server is sent, we want to perform some actions based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.

When readyState is 4 and status is 200, the response is ready:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }


if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();

91. What is main strength of Ajax ?

ans- AJAX does not refresh or reload the whole page as because Ajax uses asynchronous technology.
In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so.

multiple table join with where clause example

Sections
Section Table
SectionMembers
Section Members Table
MemberStatus
Member Status Table

select s.section_id,  s.title,  s.description,  m.status
from Sections s left join SectionMembers sm  on s.section_id = sm.section_id
  and sm.memberid = 200 left join MemberStatus m  on sm.status_code = m.status_code
where s.section_ownerid = 100;
 results as shown below
ote: while your desired result shows that section_id=2 has a status of ActiveMember there is no way in your sample data to make this value link to section 2.
This query gives the result:
| SECTION_ID |  TITLE | DESCRIPTION |         STATUS |
------------------------------------------------------
|          1 | title1 |       desc1 |  PendingMember |
|          2 | title2 |       desc2 | MemberRejected |
|          3 | title3 |       desc3 | MemberRejected |
|          4 | title4 |       desc4 |   ActiveMember |
|          5 | title5 |       desc5 |         (null) |
|          6 | title6 |       desc6 |         (null) |

Difference between Self and Equi Join in SQL - INNER Join example MySQL

Difference between Self and Equi Join in SQL - INNER Join example MySQL

Main difference between Self Join and Equi Join is that, In Self Join we join one table to itself rather than joining two tables. Both Self Join and Equi Join are types of INNER Join in SQL but there is subtle difference between two. Any INNER Join with equal as join predicate is known as Equi Join. SQL Joins are fundamental concept of SQL similar to correlated and noncorrelated subqueries or using group by clause and good understanding of various types of SQL join is must for any programmer. By the way If you have written INNER join using where clause than using comparison operator as = will be known as equi join. Equi join or Self join are not a formal join or part of syntax, instead they are just popular way to refer certain join examples. One of the best example of Self Join, I have seen in SQL Interview questions is "How do you find all Employees who are Managers in Employee table", which is commonly asked along with another popular question how to find second highest salary of employee or questions related to join three tables in one sql query. In this SQL tutorial we will learn self join by example while solving this SQL query.

Self Join Example in SQL

In order to solve this query let's first see schema and data of Employee table.
mysql> select * from employee;
+--------+----------+---------+--------+--------+
| emp_id | emp_name | dept_id | salary | mgr_id |
+--------+----------+---------+--------+--------+
|    103 | Jack     |       2 |   1400 |    104 |
|    104 | John     |       2 |   1450 |    104 |
|    105 | Johnny   |       3 |   1050 |    104 |
|    108 | Alan     |       3 |   1150 |    104 |
|    106 | Virat    |       4 |    850 |    105 |
|    107 | Vina     |       4 |    700 |    105 |
|    109 | joya     |       4 |    700 |    105 |
+--------+----------+---------+--------+--------+
7 rows in set (0.00 sec)
In above  table all employees who are managers has there emp_id as mgr_id in other employees and by using SELF JOIN  i.e. join two instance of employee table and comparing, we can find all employees who are managers. Here is the SELECT query example using self join :
mysql> select distinct e.emp_id, e.emp_name from employee e join employee m on e.emp_id=m.mgr_id;
+--------+----------+
| emp_id | emp_name |
+--------+----------+
|    104 | John     |
|    105 | Johnny   |
+--------+----------+
2 rows in set (0.00 sec)
difference between Self Join vs Equi Join MySQL exampleIn this example of Self Join, we have joined employee table to itself by using two table aliases e and m. We have also used distinct keyword to remove duplicates here. You can also say this is an example of EQUI JOIN because in join predicate we have used = or equal condition. In fact this one is example of INNER Join, SELF Join and EQUI Join at same time.
Self Join vs Equi Join
In short major difference between Self Join and Equi Join in SQL is that Self Join requires only one table while most of Equi join is condition used in join predicate. Since Equi Join is based on condition for comparison, it can occur in any INNER, OUTER or SELF join in SQL.
That’s all on difference between Self Join and Equi Join in SQL. Self Join is one of the important technique to solve many SQL query related problem where two columns of table contains same type of data e.g. here emp_id and dept_id are essentially same data.