Tuesday, 28 October 2014

How calulation total value for HTML input text?


<script>
$j(document).ready(function(){
$j(":text").keyup(function(){

if (isNaN($j(this).val())) {
alert('* Input digits (0 - 9).');
$j(this).val('');
}

var total = 0;  
$j(".txt").each( function(){
total += $j(this).val() * 1;
});
$j('#total').val(total);
});
});
</script>

Saturday, 25 October 2014

file_get_contents VS CURL, what has better performance?

PHP offers two main options to get a remote file, curl and file_get_contents. There are many difference between the two. Curl is a much faster alternative to file_get_contents.
Using file_get_contents to retrieve http://www.example.com/ took 0.198035001755 seconds. Meanwhile, using curl to retrieve the same file took 0.025691986084 seconds. As you can see, curl is much faster.

After googling I came to the conclusion even though curl is lot complex but it lik atleast 30% times faster than the former one.

I just did some quick benchmarking on this.
Fetching google.com using file_get_contents took (in seconds):
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
CURL took:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

file_get_contents requires allow_url_fopen to be TRUE.
allow_url_fopen = 1
 

Syntax to use file_get_contents()

$result = file_get_contents('https://www.google.co.in');

Syntax to use curl()

// Initiate the curl session
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'https://www.google.co.in');
// Removes the headers from the output
curl_setopt($ch, CURLOPT_HEADER, 0);
// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute the curl session
$result = curl_exec($ch);
// Close the curl session
curl_close($ch);
// Return the output as a variable
return $output;
 


What is PHP error levels and their numeric values as well as constant?

Error Levels

The following values and constants can be used within the error_reporting() function.
value constant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR

Basic Usage

The following is basic usage of PHP's error reporting (using only one level).
//show nothing
error_reporting(0);

//show everything
error_reporting(E_ALL);

//using php.ini and ini_set()
ini_set('error_reporting', E_ALL);


Advanced Usage

The following accounts for multiple error reporting levels.
//show warnings and errors
error_reporting(E_ERROR | ERROR_WARNING);

//show all types but notices
error_reporting(E_ALL ^ E_NOTICE);

How write/use ajax using XML format?

<html>
<head>
<script>
function showCD(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  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","getcd.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bonnie Tyler">Bonnie Tyler</option>
<option value="Dolly Parton">Dolly Parton</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>

</body>
</html>




<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++) {
  //Process only element nodes
  if ($x->item($i)->nodeType==1) {
    if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
      $y=($x->item($i)->parentNode);
    }
  }
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++) {
  //Process only element nodes
  if ($cd->item($i)->nodeType==1) {
    echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
    echo($cd->item($i)->childNodes->item(0)->nodeValue);
    echo("<br>");
  }
}
?> 

Friday, 24 October 2014

What is CURL in PHP?

Why we need PHP CURL ?
To send HTTP GET requests, simply we can use file_get_contents() method.

file_get_contens('http://hayageek.com')
But sending POST request and handling errors are not easy with file_get_contents().

Sending HTTP requests is very simple with PHP CURL.You need to follow the four steps to send request.
step 1). Initialize CURL session
1
$ch = curl_init();
step 2). Provide options for the CURL session
1
2
3
curl_setopt($ch,CURLOPT_URL,"http://hayageek.com");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
CURLOPT_URL -> URL to fetch
CURLOPT_HEADER -> to include the header/not
CURLOPT_RETURNTRANSFER -> if it is set to true, data is returned as string instead of outputting it.

step 3). Execute the CURL session
1
$output=curl_exec($ch);
step 4). Close the session

curl_close($ch);
Note: You can check whether CURL enabled/not with the following code.




$ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;

What is MYSQL Trigger?

A trigger is a rule that you put on a table which basically says, whenever you DELETE, UPDATE or INSERT something in this table, also do something else.

DROP TRIGGER IF EXISTS deleteUser;
DELIMITER |
CREATE TRIGGER deleteUser AFTER DELETE ON ul_logins
FOR EACH ROW BEGIN
  DELETE FROM userbase WHERE userID = old.id;
END;
|
DELIMITER ;
 
 
 
 
DELIMITER | 
CREATE TRIGGER `after_insert_cart_items`
AFTER INSERT ON `trigger_cart_items` 
FOR EACH ROW
    BEGIN
        INSERT INTO trigger_cart_log (cart_id, item_id)
        VALUES (NEW.cart_id, NEW.item_id);
    END
|
DELIMITER ;
 
 
 
 
DELIMITER | 
CREATE TRIGGER `after_update_cost`
    AFTER UPDATE ON `trigger_items_cost` FOR EACH ROW
    BEGIN
       UPDATE trigger_items
       SET price = (NEW.cost * 1.3)
       WHERE item_id = NEW.item_id;
    END
|
DELIMITER ;
 
 
 
 
CREATE TRIGGER `before_update_cost`
    BEFORE UPDATE ON `trigger_items_cost` FOR EACH ROW
    BEGIN
        IF NEW.cost < 50 THEN
            SET NEW.cost = 50;
        ELSEIF NEW.cost > 50 AND NEW.cost < 100 THEN
            SET NEW.cost = 100;
        END IF;
    END
 
 

Monday, 6 October 2014

What is the diffrent between HAVING and WHERE clause?

1. WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates).
2.   HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
3.   HAVING is used to check conditions after the aggregation takes place.
4.   The HAVING clause was added to SQL because the WHERE keyword could not be used with       aggregate functions.


The difference between the two is in the relationship to the GROUP BY clause:
  • WHERE comes before GROUP BY; SQL evaluates the WHERE clause before it groups records.
  • HAVING comes after GROUP BY; SQL evaluates HAVING after it groups records.
WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.

HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.

HAVING checks the condition on the query result already found. But WHERE is for checking condition while query runs.
Let me give an example to illustrate this. Suppose you have a database table like this.
 usertable{ int userid, date datefield, int dailyincome }

Suppose, the following rows are in table:
1, 2011-05-20, 100
1, 2011-05-21, 50
1, 2011-05-30, 10
2, 2011-05-30, 10
2, 2011-05-20, 20
Now, we want to get the userids and sum(dailyincome) whose sum(dailyincome)>100
If we write:
SELECT userid, sum(dailyincome) FROM usertable WHERE sum(dailyincome)>100 GROUP BY userid
This will be an error. The correct query would be:
SELECT userid, sum(dailyincome) FROM usertable GROUP BY userid HAVING sum(dailyincome)>100

How to print start in different format?

*
**
***
****
*****
******

<?php
function star($num){
    if($num==1){
        echo '*';
        return;
    }
    else{
        for($i=0; $i<$num; $i++){
            if($i==0){
                echo '*<br>';
            }
            else{
                for($j=0; $j<$i; $j++){
                    echo '*';
                }
                echo '*<br>';
            }
        }
    }
}
star(6);
?>

Thursday, 2 October 2014

How to use PHP data object?


PHP Data Object/PDO TOC Step By Step Tutorial PHP Data Object is a Database Connection Abstraction Library for PHP 5.

What is PDO?

  • a PHP5 extension written in a compiled language (C/C++)
  • a Lightweight DBMS connection abstract library (data access abstraction library)

Why PDO?

  • Support great number of database systems supported by PHP
  • You don't need rewriting of many line code for each database. Just write one and run anywhere
  • Speed. PDO written in compiled language, PHP libraries (ADOdb, PEAR DB) written in an interpreted language
  • Your software more easy to install. Do not need third party software

Whenever you need PDO?

  • You need portable application that support many database system
  • You need speed

Connect to MySQL

<?php
/*** mysql hostname ***/$hostname 'localhost';
/*** mysql username ***/$username 'username';
/*** mysql password ***/$password 'password';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=mysql"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database';
    }
catch(
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>



Connect to Firebird

<?phptry {
    
$dbh = new PDO("firebird:dbname=localhost:C:\Programs\Firebird\DATABASE.FDB""SYSDBA""masterkey");
    }  
catch (
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>

Connect to Oracle

<?phptry {
    
$dbh = new PDO("OCI:""username""password")
    }
catch (
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>

Connect to SQLite

<?phptry {
    
/*** connect to SQLite database ***/
    
$dbh = new PDO("sqlite:/path/to/database.sdb");
    }
catch(
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>

How to create MYSQL indexes?

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
While creating index, it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, indexes are also type of tables, which keep primary key or index field and a pointer to each record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to insert or update index values as well.

Simple and Unique Index:

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
 
You can use one or more columns to create an index. For example, we can create an index on tutorials_tbl using tutorial_author.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
 
You can create a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.

If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name.
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
 
 
There are four types of statements for adding indexes to a table:
  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
  • ALTER TABLE tbl_name ADD INDEX index_name (column_list): This adds an ordinary index in which any value may appear more than once.
  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): This creates a special FULLTEXT index that is used for text-searching purposes.

How to create view in mysql?

A database view is a virtual table or logical table which is defined as a SQL query with joins. Because a database view is similar to a database table, which consists of rows and columns, so you can query data against it. Most database management systems, including MySQL, allows you to update data in the underlying tables through the database view with some prerequisites. 
A database view is dynamic because it is not related to the physical schema. The database system stores database views as a SQL Select statement with joins. When the data of the tables changes, the view reflects that changes as well.

Advantages of database view

 The following are advantages of using database views.
  • A database view allows you to simplify complex queries: a database view is defined by an SQL statement that associates with many underlying tables. You can use database view to hide the complexity of underlying tables to the end-users and external applications. Through a database view, you only have to use simple SQL statements instead of complex ones with many joins.
  • A database view helps limit data access to specific users. You may not want a subset of sensitive data can be queryable by all users. You can use database views to expose only non-sensitive data to a specific group of users.
  • A database view provides extra security layer. Security is a vital part of any relational database management system. Database views provides extra security for a database management system. A database view allows you to create only read-only view to expose read-only data to specific users. Users can only retrieve data in read-only view but cannot update it.
  • A database view enables computed columns. A database table should not have calculated columns however a database view should. Suppose in the orderDetails table you have quantityOrder (the number of ordered products) and priceEach (price per product item) columns. However the orderDetails table does not have computed column to store total sales for each line item of the order. If it has, the database schema would not be a good design. In this case, you can create a computed column named total, which is a product of quantityOrder and priceEach to store the computed result. When you query data from the database view, the data of the computed column is calculated on fly.
  • Database view enables backward compatibility. Suppose you have a central database, which many applications are using it. One day you decided to redesign the database to adapt with the new business requirements. You remove some tables and create several new tables, and you don’t want the changes affect other applications. In this scenario, you can create database views with the same schema as the legacy tables that you’ve removed.

Disadvantages of database view

 Besides the advantages above, there are several disadvantages of using database views:
  • Performance: querying data from a database view can be slow especially if the view is created based on other views.
  • Tables dependency: you create view based on underlying tables of the a database. Whenever you change the structure of those tables that view associates with, you have to change the view as well.

Some rules to create updatable view:

  • The SELECT statement must only refer to one database table.
  • The SELECT statement must not use GROUP BY or HAVING clause.
  • The SELECT statement must not use DISTICT in the column list of the SELECT clause.
  • The SELECT statement must not refer to read-only views.
  • The SELECT statement must not contain any expression (aggregates, functions, computed columns…)

Create a simple view

CREATE VIEW student_details
   AS SELECT s.id, s.name sname, d.name dname, c.name cname
FROM student AS s
INNER JOIN district AS d ON s.district = d.id
INNER JOIN course AS c ON s.course = c.id;

Create view with JOIN

CREATE VIEW customerOrders AS
SELECT  D.orderNumber,
         customerName,
         SUM(quantityOrdered * priceEach) total
FROM orderDetails D
INNER JOIN orders O ON O.orderNumber = D.orderNumber
INNER JOIN customers C ON O.customerNumber =  C.customerNumber  
GROUP BY D.orderNumber
ORDER BY total DESC;

Create view with subquery

CREATE VIEW vwProducts  AS
SELECT productCode,
        productName,
        buyPrice
FROM products
WHERE buyPrice > (
      SELECT AVG  (buyPrice)
      FROM  products
)
ORDER BY buyPrice DESC

 

 

Saturday, 27 September 2014

How to check the internet connection using PHP function fsockopen?

<?php
//function to check if the local machine has internet connection
function checkConnection()
{
    //Initiates a socket connection to www.itechroom.com at port 80
    $conn = @fsockopen("www.itechroom.com", 80, $errno, $errstr, 30);
    if ($conn)
    {
        $status = "Connection is OK";
        fclose($conn);
    }
    else
    {
        $status = "NO Connection<br/>\n";
        // $status .= "$errstr ($errno)";
    }
    return $status;
}

echo checkConnection();
?>

How to print string in reverse order using recursion?

function reverse_recursion($str){
    if(strlen($str)==1)
        return $str;
    else{
        $len = strlen($str);
        return ucwords(reverse_recursion(substr($str,1,strlen($str)-1)).$str[0]);
    }
}


echo reverse_recursion('Kumar Abhimanyu');

How to print string in reverse order without recursion?

function reverse($str){
    $rev = NULL;
    for($i=strlen($str)-1; $i>=0; $i--)
        $rev.=$str[$i];
        return ucwords(strtolower($rev));
}
echo reverse('Kumar Abhimanyu');

How to print facorial in PHP using recursion?

function fact($n){
    if($n==1)
        return $n;
    else
        return fact($n-1)*$n;
}


echo fact(4);

How tp print Fibonacci Series in PHP?

function fab($max=null){
    $a = 0;
    $b = 1;
    $count = 0;
    echo $a.', ';
    echo $b.', ';
    while($count < $max){
        $c = $b + $a;
        echo $c.', ';
        $a = $b;
        $b = $c;
        $count++;
    }
}

echo fab(22);

It will print up to22.

Tuesday, 23 September 2014

How to create tebbing system?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tabs - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
</body>
</html>

How to create text box tooltip?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tooltip - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( document ).tooltip();
});
</script>
<style>
label {
display: inline-block;
width: 5em;
}
</style>
</head>
<body>
<p><a href="#" title="That&apos;s what this widget is">Tooltips</a> can be attached to any element. When you hover
the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip.</p>
<p>But as it's not a native tooltip, it can be styled. Any themes built with
<a href="http://jqueryui.com/themeroller/" title="ThemeRoller: jQuery UI&apos;s theme builder application">ThemeRoller</a>
will also style tooltips accordingly.</p>
<p>Tooltips are also useful for form elements, to show some additional information in the context of each field.</p>
<p><label for="age">Your age:</label><input id="age" title="We ask for your age only for statistical purposes."></p>
<p>Hover the field to see the tooltip.</p>
</body>
</html>

How to create dialog box alert in jquery?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {

$( "#aaa" ).click(function() {
$( "#dialog" ).dialog();
});
});
</script>
</head>
<body>
<div id="dialog" style="display:none;" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<span id="aaa">Click Here</span>
</body>
</html>

How to create progressbar using jquery?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Progressbar - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#progressbar" ).progressbar({
value: 37
});
});
</script>
</head>
<body>
<div id="progressbar"></div>
</body>
</html>

How to create Autocomplete textbox

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>

How to create parent child menu

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Menu - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#menu" ).menu();
});
</script>
<style>
.ui-menu { width: 150px; }
</style>
</head>
<body>
<ul id="menu">
<li class="ui-state-disabled">Aberdeen</li>
<li>Ada</li>
<li>Adamsville</li>
<li>Addyston</li>
    <li>Delphi
        <ul>
        <li class="ui-state-disabled">Ada</li>
        <li>Saarland</li>
        <li>Salzburg an der schönen Donau</li>
        </ul>
    </li>
    <li>Saarland</li>
    <li>Salzburg
        <ul>
            <li>Delphi
                <ul>
                    <li>Ada</li>
                    <li>Saarland</li>
                    <li>Salzburg</li>
                </ul>
            </li>
            <li>Delphi
                <ul>
                    <li>Ada</li>
                    <li>Saarland</li>
                    <li>Salzburg
                        <ul>
                            <li>Ada</li>
                            <li>Saarland</li>
                            <li>Salzburg
                                <ul>
                                    <li>Ada</li>
                                    <li>Saarland</li>
                                    <li>Salzburg
                                        <ul>
                                            <li>Ada</li>
                                            <li>Saarland</li>
                                            <li>Salzburg</li>
                                        </ul>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li>Perch</li>
        </ul>
    </li>
<li class="ui-state-disabled">Amesville</li>
</ul>
</body>
</html>

Monday, 22 September 2014

Browser detection - IE, Firefox, Safari, Chrome

    <?php
    $msie = strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE') ? true : false;
    $firefox = strpos($_SERVER["HTTP_USER_AGENT"], 'Firefox') ? true : false;
    $safari = strpos($_SERVER["HTTP_USER_AGENT"], 'Safari') ? true : false;
    $chrome = strpos($_SERVER["HTTP_USER_AGENT"], 'Chrome') ? true : false;
    ?>
   
        <?php
    //Firefox
    if ($firefox) {
    echo 'you are using Firefox!';
    echo '<br />';
    }
    
    // Safari or Chrome. Both use the same engine - webkit
    if ($safari || $chrome) {
    echo 'you are using a webkit powered browser';
    echo '<br />';
    }
    
    // IE
    if ($msie) {
    echo '<br>you are using Internet Explorer<br>';
    echo '<br />';
    }
    
    // Not IE and for all other browsers
    if (!$msie) {
    echo '<br>you are not using Internet Explorer<br>';
    echo '<br />';
    }
    
    // Add inline css
    if ($firefox) {
    echo '<style type="text/css">';
    echo '.mydiv {position:relative; width:100px; height:50px;}';
    echo '</style>';
    }
    ?>

Some useful link

Autocomplete textbox
   http://daveismyname.com/demos/autocomplete/
Dynamick datepicker
   http://www.daveismyname.com/demos/dynamic-form-with-jquery-ui-datepicker/

Create dynamic datepicker in jquery

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Form with Jquery UI datepicker</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
</head>
<body>

<form action="" method="post">

<fieldset>
<legend>Inputs</legend>
<div id="extender"></div>
<p><a href="#" id="add">Add</a></p>
</fieldset>

</form>

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {

//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).empty();
return false;
});
});

var options = '<p>Title: <input type="text" name="titles[]" value="" size="30" /> Date: <input type="text" class="datepicker" name="dates[]" value="" size="10" /> <a href="#" class="remove">Remove</a></p>';   

//add input
$('a#add').click(function() {
$(options).fadeIn("slow").appendTo('#extender');
i++;   
return false;
});

$('.datepicker').live('click', function() {
$(this).datepicker('destroy').datepicker({changeMonth: true,changeYear: true,dateFormat: "yy-mm-dd",yearRange: "1900:+10",showOn:'focus'}).focus();
});


});
</script>
</body>
</html>

Geting image size before image upload using javascript

<SCRIPT type="text/javascript">
    function ValidateFileUpload() {
        var fuData = document.getElementById('fileChooser');
        var FileUploadPath = fuData.value;
var f = fuData.files.item(0); // get only the first file from the list of files
var filesize = f.size;
alert("the size of the image is : "+filesize/1024+" bytes");

//To check if user upload any file
        if (FileUploadPath == '') {
            alert("Please upload an image");

        } else {
            var Extension = FileUploadPath.substring(
                    FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

//The file uploaded is an image

if (Extension == "gif" || Extension == "png" || Extension == "bmp"
                    || Extension == "jpeg" || Extension == "jpg") {

// To Display

                if (fuData.files && fuData.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function(e) {
                        $('#blah').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(fuData.files[0]);
                }

            }

//The file upload is NOT an image
else {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
fuData.value="";
            }
        }
    }
</SCRIPT>



<form>
<input type="text" />
<input type="file" name="dataFile" id="fileChooser" onchange="return ValidateFileUpload()" />
<input type="reset" />
</form>

Get image extention before uploading using javascript

<SCRIPT type="text/javascript">
    function ValidateFileUpload() {
        var fuData = document.getElementById('fileChooser');
        var FileUploadPath = fuData.value;
// var f = fuData.files.item(0); // get only the first file from the list of files
// var filesize = f.size;
// alert("the size of the image is : "+filesize/1024+" bytes");

//To check if user upload any file
        if (FileUploadPath == '') {
            alert("Please upload an image");

        } else {
            var Extension = FileUploadPath.substring(
                    FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

//The file uploaded is an image

if (Extension == "gif" || Extension == "png" || Extension == "bmp"
                    || Extension == "jpeg" || Extension == "jpg") {

// To Display

                if (fuData.files && fuData.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function(e) {
                        $('#blah').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(fuData.files[0]);
                }

            }

//The file upload is NOT an image
else {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
fuData.value="";
            }
        }
    }
</SCRIPT>
<form>
<input type="text" />
<input type="file" name="dataFile" id="fileChooser" onchange="return ValidateFileUpload()" />
<input type="reset" />
</form>

Thursday, 6 March 2014

Wordpress Interview Question and Answer.

1. How to get the postid in wordpress?
We can get the postid
global $wp_query;
$postid = $wp_query->post->ID;
echo $postid;

2. How to get the post meta value in worpdress?
We can get the post meta value throw postid.
 For example here post Custom Field name : comapny name
 get_post_meta($postid, 'Company name', true);

3. How to check if the post has a Post Thumbnail assigned to it.
if ( has_post_thumbnail() )  // check if the post has a Post Thumbnail assigned to it.
   {                                
      the_post_thumbnail();  
   }

4.how to get the wordpress featued image and how to change the image width and height.
We can get the featurd image wordpress function
   the_post_thumbnail(); //here we can get the wordpress featured image thumbnail
  the_post_thumbnail( array(100,100) );     // here we can change the image size.

5. How to get the specified category post only in wordpress?
Here we can get the all post in category id based.
<?php query_posts("cat=106 && per_page=5");// here 106 is the category id  ?>
<?php while ( have_posts() ) : the_post(); ?>
<h3><?php the_title(); // here we can get the post title. this is the wordpress free defind function ?></h3>
<?php  endwhile; ?>

6. How to hide the top admin bar at the frontend of wordpress 3.4?
Add the below mentioned code in the theme(active) function.php 
add_filter(‘show_admin_bar’, ‘__return_false’);
                               (or)
Add the below code in the active theme stylesheet
#wpadminbar {
display: none; visibility: hidden;
}
7. Run Any Query on the Database for WordPress.
The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function (see below), however, for SELECT queries.
 <?php $wpdb->query('query'); ?>
8. What are rules to follow in wordpress plugin development?
  • Find a unique name
  • Setup a prefix (related to your brand)
  • Create the plugin’s folder
  • Create sub-folders for PHP files, assets, and translations
  • Create the main plugin file and fill in obligatory header information
  • Create a readme.txt file
  • Use proper constants and functions to detect paths to plugin files
  • Create additional PHP files and include them inside the main one
  • Create activation and deactivation functions
  • Create an uninstall script

9. What is hooks and types of hooks in wordpress?
Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:
  1. Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.
  2. Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.

10. Can I rename the WordPress folder?
If you have not already installed WordPress, you can rename the folder with the WordPress files, before, or even after uploading the files.
If you have already installed WordPress, and you want to rename the folder, login to the weblog as the administrator and change the following settings in Settings > General:
WordPress address (URI):
Blog address (URI):
Once you have done this, you can rename the directory or folder with the WordPress files in it.
11. Do I really need MySQL?
You certainly need the MySQL database server to power your WordPress blog. In fact, WordPress only supports the MySQL database server. Listed are the PHP and MySQL requirements:
WordPress server requirements for Version 3.2:
PHP version 5.2.4 or greater
MySQL version 5.0.15 or greater
(Optional)(Required for MultiSite) Apache mod_rewrite module (for clean URIs known as Permalinks)
12. Why does WordPress use MySQL?
MySQL is extremely fast. It is also the most widely available database server in the world. Open-source and free, MySQL is supported by thousands of low-cost Linux (and Windows!) hosts, which means a very low barrier to entry for anyone wanting to start a WordPress (or database-driven) website. MySQL’s documentation is useful, cogent and thorough. (Note: it may be intimidating if you are new to all this.) Add to all that the fact that users are able to directly manipulate MySQL with phpMyAdmin, developed expressly for that purpose, and it is obvious that MySQL is the best choice. Of course, WordPress insists on the best.
13. How do I disable comments?
First, unchecked Allow people to post comments on the article on the Options > Discussion panel. This will only disable comments on future posts. Now, to completely disable comments, you will have to edit each past post and uncheck Allow Comments from the Write Post SubPanel. Alternatively, you could run this MySQL query from the command line on a shell account or using phpMyAdmin: UPDATE wp_posts SET comment_status=”closed”;
If your goal is to permanently disable comments, then you should delete the wp-comments-post.php file as well.
14. What are the features of Wordpress?
  • Simplicity Simplicity makes it possible for you to get online and get publishing, quickly. Nothing should get in the way of you getting your website up and your content out there. WordPress is built to make that happen.
  • Flexibility With WordPress, you can create any type of website you want: a personal blog or website, a photoblog, a business website, a professional portfolio, a government website, a magazine or news website, an online community, even a network of websites. You can make your website beautiful with themes, and extend it with plugins. You can even build your very own application.
  • Publish with Ease If you’ve ever created a document, you’re already a whizz at creating content with WordPress. You can create Posts and Pages, format them easily, insert media, and with the click of a button your content is live and on the web.
  • Publishing Tools WordPress makes it easy for you to manage your content. Create drafts, schedule publication, and look at your post revisions. Make your content public or private, and secure posts and pages with a password.
  • User Management Not everyone requires the same access to your website. Administrators manage the site, editors work with content, authors and contributors write that content, and subscribers have a profile that they can manage. This lets you have a variety of contributors to your website, and let others simply be part of your community.
  • Media Management They say a picture says a thousand words, which is why it’s important for you to be able to quickly and easily upload images and media to WordPress. Drag and drop your media into the uploader to add it to your website. Add alt text, captions, and titles, and insert images and galleries into your content. We’ve even added a few image editing tools you can have fun with.
  • Full Standards Compliance Every piece of WordPress generated code is in full compliance with the standards set by the W3C. This means that your website will work in today’s browser, while maintaining forward compatibility with the next generation of browser. Your website is a beautiful thing, now and in the future.
  • Easy Theme System WordPress comes bundled with two default themes, but if they aren’t for you there’s a theme directory with thousands of themes for you to create a beautiful website. None of those to your taste? Upload your own theme with the click of a button. It only takes a few seconds for you to give your website a complete makeover.
  • Extend with Plugins WordPress comes packed full of features for every user, for every other feature there’s a plugin directory with thousands of plugins. Add complex galleries, social networking, forums, social media widgets, spam protection, calendars, fine-tune controls for search engine optimization, and forms.
  • Built-in Comments Your blog is your home, and comments provide a space for your friends and followers to engage with your content. WordPress’s comment tools give you everything you need to be a forum for discussion and to moderate that discussion.
  • Search Engine Optimized When the head of Google’s web spam team says that WordPress is a great choice, taking care of 80-90% of the mechanics of search engine optimization for you, you know you’re on to a good thing. For more fine-grained SEO control, there are plenty of SEO plugins to take care of that for you.
  • Multilingual WordPress is available in more than 70 languages. If you or the person you’re building the website for would prefer to use WordPress in a language other than English, that’s easy to do.
  • Easy Installation and Upgrades WordPress has always been easy to install and upgrade. If you’re happy using an FTP program, you can create a database, upload WordPress using FTP, and run the installer. Not familiar with FTP? Plenty of web hosts offer one-click WordPress installers that let you install WordPress with, well, just one click!
  • Importers Using blog or website software that you aren’t happy with? Running your blog on a hosted service that’s about to shut down? WordPress comes with importers for blogger, LiveJournal, Movable Type, TypePad, Tumblr, and WordPress. If you’re ready to make the move, we’ve made it easy for you.
  • Own Your Data Hosted services come and go. If you’ve ever used a service that disappeared, you know how traumatic that can be. If you’ve ever seen adverts appear on your website, you’ve probably been pretty annoyed. Using WordPress means no one has access to your content. Own your data, all of it – your website, your content, your data.
  • Freedom WordPress is licensed under the GPL which was created to protect your freedoms. You are free to use WordPress in any way you choose: install it, use it, modify it, distribute it. Software freedom is the foundation that WordPress is built on.
  • Community As the most popular open source CMS on the web, WordPress has a vibrant and supportive community. Ask a question on the support forums and get help from a volunteer, attend a WordCamp or Meetup to learn more about WordPress, read blogs posts and tutorials about WordPress. Community is at the heart of WordPress, making it what it is today.
  • Contribute You can be WordPress too! Help to build WordPress, answer questions on the support forums, write documentation, translate WordPress into your language, speak at a WordCamp, write about WordPress on your blog. Whatever your skill, we’d love to have you!

Developer Features

For developers, we’ve got lots of goodies packed under the hood that you can use to extend WordPress in whatever direction takes your fancy.
  • Plugin System The WordPress APIs make it possible for you to create plugins to extend WordPress. WordPress’s extensibility lies in the thousands of hooks at your disposal. Once you’ve created your plugin, we’ve even got a plugin repository for you to host it on.
  • Theme System Create WordPress themes for clients, customers, and for WordPress users. TheWordPress API provides the extensibility to create themes as simple or as complex as you wish. If you want to give your theme away for free you can give it to users in the Theme Repository
  • Application Framework If you want to build an application, WordPress can help with that too. Under the hood WordPress provides a lot of the features that your app will need, things like translations, user management, HTTP requests, databases, URL routing and much, much more.
  • Custom Content Types WordPress comes with default content types, but for more flexibility you can add a few lines of code to create your own custom post typestaxonomies, and metadata. Take WordPress in whatever direction you wish.
  • The Latest Libraries WordPress comes with the latest script libraries for you to make use of. These include jQuery, Plupload, Underscore.js and Backbone.js. We’re always on the lookout for new tools that developers can use to make a better experience for our users.
15. Who is the founder of WordPress?
      Matthew Charles Mullenweg.
16. How many tables a default WordPress will have?
A default wordpress will have 11 tables. They are-
1. wp_commentmeta
2. wp_comments
3. wp_links
4. wp_options
5. wp_postmeta
6. wp_posts
7. wp_terms
8. wp_term_relationships
9. wp_term_taxonomy
10.wp_usermeta
11.wp_users

How calulation total value for HTML input text?

<script> $j(document).ready(function(){ $j(":text").keyup(function(){ if (isNaN($j(this).val())) { alert(...