Thursday, May 16, 2013

Php encrypt decrypt url

When developing web applications sometimes we encounter situations where we need to encrypt/decrypt url or some code or some information. For such situations I wrote a simple php script using the default php functions:
base64_encode()
base64_decode()
Now the use of these functions is quite simple. For example if you want to pass some critical information like password in the url like:


Example:
Encode:- http://www.abc.com/abc.php?param0=<?php echo base64_encode('blog'); ?>

Example:


<?php
$param0 = $_REQUEST['param0
'];

echo base64_decode(
$param0
);
?>

Tuesday, May 14, 2013

Php device detection

<?php

//Detect special conditions devices
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
    //browser reported as an iPhone/iPod touch -- do something here
}else if($iPad){
    //browser reported as an iPad -- do something here
}else if($Android){
    //browser reported as an Android device -- do something here
}else if($webOS){
    //browser reported as a webOS device -- do something here
}

?>

Sunday, May 12, 2013

RECURSIVE Function in PHP


A recursive function is just a function that calls itself.

Things to take care of Using Recursive Function

1. Every recursive function must have the terminating condition
2. The function must call the function itself and Each recursive call must be different than the one before.

Example

1)
// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {

if ($n == 1) return 1;
return $n * factorial($n-1);

}
echo factorial(5); // Outputs 120


2)
// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);

function sum_array($array) {

$total = 0;
foreach ($array as $element) {
if(is_array($element)) {
$total += sum_array($element);
} else {
$total += $element;
}
}
return $total;

}
echo sum_array($example); // Outputs 67

Wednesday, May 8, 2013

Get Joomla! 1.7 Plugin, Module, Component and Template Parameters

Plugin parameters from inside a plugin

$param = $this->params->get('paramName', defaultValue);

Plugin parameters from outside a plugin

$plugin = JPluginHelper::getPlugin('editors', 'codemirror');
$pluginParams = new JRegistry();
$pluginParams->loadString($plugin->params);
$param = $pluginParams->get('paramName', 'defaultValue');

Module parameters from inside a module

$param = $params->get('paramName', 'defaultValue');

Module parameters from outside a module

$module = JModuleHelper::getModule('banners');
$moduleParams = new JRegistry();
$moduleParams->loadString($module->params);
$param = $moduleParams->get('paramName', 'defaultValue');

Component parameters from inside a component

$app = JFactory::getApplication('site');
$componentParams = $app->getParams('com_content');
$param = $componentParams->get('paramName', defaultValue);

Component parameters from outside a component

$app = JFactory::getApplication('site');
$componentParams = $app->getParams('com_example');
$param = $componentParams->get('paramName', defaultValue);

Template parameters from inside a template

$param = $this->params->get('paramName', defaultValue);

Template parameters from outside a template

$app = JFactory::getApplication('site');
$template = $app->getTemplate(true);
$param = $template->params->get('paramName', defaultValue);

oops interview questions and answers

1:What is Object Oriented Programming ?
It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.
OR
Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined and cooperating objects.

2:What is a Class ?

A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type which represents a blue print of objects. It’s a template of object.
OR
Class is a template for a set of objects that share a common structure and a common behavior.

3:What is an Object ?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.
OR
Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.
5:What is the relation between Classes and Objects?
They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed, Brakes, Type of Car etc.Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality.
6:What is an Abstract class ?
Abstract class defines an abstract concept which can not be instantiated and comparing o interface it can have some implementation while interfaces can not. Below are some
points for abstract class:-
=>We can not create object of abstract class it can only be inherited in a below class.
=> Normally abstract classes have base implementation and then child classes derive from the abstract class to make the class concrete.

7:What is POLYMORPHISM in oop?
Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.
for more details
http://www.youtube.com/watch?v=PAMDmFXou5I&feature=related
8:What is meant by static binding?
Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.
9:What is meant by Dynamic binding?
Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.
10: What is the use of friend function?
Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.
11:Explain about encapsulation?
Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.
12:Static Keyword
* To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
* Static properties or methods can be accessible without needing an instantiation of the class.
* A property declared as static can not be accessed with an instantiated class object.
* $this is not available inside the method declared as static.
* Static properties cannot be accessed using the arrow operator ->.
* Static properties can be accessed using the Scope Resolution Operator (::) operator.
ClassName::$staticvar= $value;
Example:
class Box
{
static private $color;
function __construct($value)
{
if($value != "")
{
Box::$color = $value;
}
$this->getColor();
}
public function getColor ()
{
echo Box::$color;
}
}
$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>
OUTPUT:
RED
GREEN
GREEN
13: What is Inheritance in OOPS?
Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (concept) of object-oriented programming
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes
The Class whose methods and variables are defined is called super class or base class
The Class that inherits methods and variables are defined is called sub class or derived class
Sometimes base class known as generalized class and derived class known as specialized class.
Benefits of using Inheritance
Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
Code reusability increased through inheritance
Inheritance provide a clear model structure which is easy to understand without much complexity
Using inheritance, classes become grouped together in a hierarchical tree structure
Code are easy to manage and divided into parent and child classes

14. What is Compile Time Polymorphism in OOPS?
Compile time Polymorphism also known as method overloading
Method overloading means having two or more methods with the same name but with different signatures.
15. What is Run Time Polymorphism in OOPS?
Run time Polymorphism also known as method overriding
Method overriding means having two or more methods with the same name , same signature but with different implementation.
16:Access modifier:
OOP provides data-hiding capabilities with public, protected, and private data attributes and methods:
Public : A public variable or method can be accessed directly by any user of the class.
Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.
Private:A private variable or method can only be accessed internally from the class in which it is defined.
17:Serialization/UnSerialization:
* Generates a storable representation of a value.
* serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.
* unserialize() can use this string to recreate the original variable values.
* This process makes a storable representation of a value that is useful for storing or passing PHP values.
* To make the serialized string into a PHP value again, use unserialize().
Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.
18:What can you Serialize and Unserialize?
* Variables
* Arrays
* Objects
19: What cannot you Serialize and Unserialize?
* Resource-type
20: What is a Virtual Function ?
Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function
21:What is a virtual class?
In multiple inheritance when a class D is derived by two base classes B and C and both base class is also inherite by same class A then then class D will get duplicate copy of uppper most base class A.In this case class A will declare as virtual class.
22:What is the difference between a virtual function and pure virtual function?
The main difference is the body of function.
Vartual Function have a function body.
We define them as :
Virtual int virFun();
A pure virtual functions doesn't have a body.
We define them as:
Virtual int myFun() = 0;
Pure virtual functions have no body and MUST be overloaded in the derived classes. You cannot create an instance of a class having a pure virtual function, the need is to inherit from it and overload the all pure virtual functions.
23:Why destructor is not over loaded?
Normally (in fact almost always) you never explicitly call the destructor, it is automatically called by the C++ frame work when the object is deleted/goes out of scope. Therefore you would not need to overload the destructor because the frame work always calls the default destructor.
24:Diversities between an abstract method & virtual method ?
An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.
25:Can we declare private class in a Namespace?
No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.
Reason: The message says it all. Classes can only be declared as private, protected or protected internal when declared as nested classes, other than that, it doesn't make sense to declare a class with a visibility that makes it unusable, even in the same module. Top level classes cannot be private, they are "internal" by default, and you can just make them public to make them visible from outside your DLL.
26:What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the inheriting.
27:What is namespace?
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }

Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example:
namespace general { int a, b; } In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.
28:What is friend function?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.
Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time.

Mysql Interview questions and answers

1:What's MySQL ?

MySQL (pronounced "my ess cue el") is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL and tailor it to their needs in accordance with the general public license. MySQL is noted mainly for its speed, reliability, and flexibility.

2:What is DDL, DML and DCL ?

If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.

3:How do you start and stop MySQL on Windows?
- net start MySQL, net stop MySQL

4: How do you start MySQL on Linux?

- /etc/init.d/mysql start

5:How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password "newpassword"

6:Explain the difference between MyISAM Static and MyISAM Dynamic.

In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.

7:What does myisamchk do?

It compressed the MyISAM tables, which reduces their disk usage.

8:Explain advantages of MyISAM over InnoDB?

Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.

9:What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?

It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.

10: What happens if a table has one column defined as TIMESTAMP?
That field gets the current timestamp whenever the row gets altered.

11: But what if you really want to store the timestamp data, such as the publication date of the article?
Create two columns of type TIMESTAMP and use the second one for your real data.

12:What Is Primary Key?

A primary key is a single column or multiple columns defined to have unique values that can be used as row identifications.

13:What Is Foreign Key?
A foreign key is a single column or multiple columns defined to have values that can be mapped to a primary key in another table.

14:What Is Index?
An index is a single column or multiple columns defined to have values pre-sorted to speed up data retrieval speed.

15:What Is View?
A view is a logical table defined by a query statement.

16:What Is Transaction?

A transaction is a logical unit of work requested by a user to be applied to the database objects. MySQL server introduces the transaction concept to allow users to group one or more SQL statements into a single transaction, so that the effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).

17:What Is Commit?

Commit is a way to terminate a transaction with all database changes to be saved permanently to the database server.

18:What Is Rollback?
Rollback is a way to terminate a transaction with all database changes not saving to the database server.

19:When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?
1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column .

20:How do you get the number of rows affected by query?

SELECT COUNT (user_id) FROM users would only return the number of user_id’s.

21:If the value in the column is repeatable, how do you find out the unique values?
Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
22:How do you return the a hundred books starting from 25th?
SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
23:What types of privileges are there in MySQL ?
There are 4 types of privileges.
i). Global privileges like *.* (all hosts connecting to Mysql db server)
Ex: GRANT SELECT, INSERT ON *.* TO ‘someuser’@'somehost’;
ii). Database privileges like .*
Ex: GRANT SELECT, INSERT ON mydb.* TO ‘someuser’@'somehost’;
iii). Table privileges like SELECT, INSERT, UPDATE, DELETE
Ex: GRANT SELECT, INSERT ON mydb.mytbl TO ‘someuser’@'somehost’;
iv). Column privileges like
Ex: GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO ‘someuser’@'somehost’;
24:How do I grant permission to a specific host ?
Command: GRANT ALL ON *.* TO ‘user_name’@'host_name’ IDENTIFIED BY ‘password’ ;
Ex: GRANT ALL ON *.* TO ‘test_app’@'sustain-75.central’ IDENTIFIED BY ‘testapp123';
25:Is it possible to insert multiple rows using single command in MySQL ?
Yes. Please see below example.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9) ;
26:How do you return the a hundred books starting from 25th?
SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
27:When would you use ORDER BY in DELETE statement?
When you’re not deleting by row ID. Such as in DELETE FROM employee ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table temployee.
28:How would you delete a column?
ALTER TABLE employee DROP phone.
29:How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
30:What are HEAP tables in MySQL?
HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
31:What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
32: What is REPLCAE statement, and how do I use it?
The REPLACE statement is the same as using an INSERT INTO command. The syntax is pretty much the same. The difference between an INSERT statement and a REPLACE statement is that MySQL will delete the old record and replace it with the new values in a REPLACE statement, hence the name REPLACE.

33: Do all unique keys have to be primary keys?
No. MySQL permits only one primary key per table, but there may be a number of unique keys. Both unique keys and primary keys can speed up the selecting of data with a WHERE clause, but a column should be chosen as the primary key if this is the column by which you want to join the table with other tables.

34:How many databases can one MySQL RDBMS contain?
Because MySQL uses the file system of the operating system, there really is no limit to the number of databases contained within a single MySQL RDBMS. The size of the database is limited by the operating system. The database tables can only be as big as the OS's file system will allow.

35:I want to sort the values of my ENUM and SET columns. How do I do this?
The sort order depends on the order in which the values were inserted. ENUM and SET types are not case sensitive. The value that is inserted reverts to the value that you used when you created the ENUM or SET.

36:What do I do if I forget the MySQL root password?
First log in to the system as the same person who is running the mysqld
daemon (probably root). Kill the process, using the kill command.
Restart MySQL with the following arguments:
bin/mysqld Skip-grant
USE mysql;
UPDATE user SET password = password('newpassword') WHERE User = 'root';
Exit
bin/mysqladmin reload
The next time you log in, you will use your new password

37: Where is the data stored in a MySQL database?

MySQL uses files to store data. These files are under the data/databasename directory, where databasename is the name of the database. There are three file types: .ISM, .FRM, and .ISD. The .FRM file contain the table schema. The .ISD is the file that actually holds the data. The .ISM file is the file that provides quick access between the two of them.

38:Explain "REPAIR TABLE" statement?

The REPAIR TABLE statement corrects problems in a table that has become corrupted. It works only for MyISAM tables.

39:Explain "OPTIMIZE TABLE" statement?

The OPTIMIZE TABLE statement cleans up a MyISAM table by defragmenting it. This involves reclaiming unused space resulting from deletes and updates, and coalescing records that have become split and stored non-contiguously. OPTIMIZE TABLE also sorts the index pages if they are out of order and updates the index statistics.

40:What is the difference between CHAR AND VARCHAR?

The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved.
The length of a CHAR column is fixed to the length that you declare when you create the table.
The length can be any value between 1 and 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed.

41:what is difference between primary key and candidate key?
Primary Key
- are used to uniquely identify each row of the table. A table can have only one primary Key.
Candidate Key
- primary key is a candidate key. There is no difference. By common convention one candidate key is designated as a “primary” one and that key is used for any foreign key references.

42:What is the difference between mysql_fetch_array and mysql_fetch_object?

mysql_fetch_array(): - returns a result row as a associated array, regular array from database.
mysql_fetch_object: - returns a result row as object from database.
43:Self join in Mysql:
Self join is a method of centralizing relational data to a single table.A self-join joins the table to itself.
Example:
CREATE TABLE employees (
NAME VARCHAR(20),
email VARCHAR(20),
mobile VARCHAR(20),
sex CHAR(1),
birth_date DATE,
);
INSERT INTO employees VALUES ('xyz','xyz@example.com','11212','F','1985-06-05');
INSERT INTO employees VALUES ('abc','abc@example.com','11111','M','1985-03-05');
INSERT INTO employees VALUES ('abc1','abc1@example.com','21111','M','1987-03-05');
SELECT e1.name, e2.name,e1.email
FROM employees AS e1, employees AS e2
WHERE e1.email = e2.email AND e1.sex = 'F' AND e2.sex = 'M';

43:How MySQL Optimizes LEFT JOIN and RIGHT JOIN ?

A LEFT JOIN B in MySQL is implemented as follows:
The table B is set to be dependent on table A and all tables that A is dependent on.
The table A is set to be dependent on all tables (except B) that are used in the LEFT JOIN condition.
All LEFT JOIN conditions are moved to the WHERE clause.
All standard join optimizations are done, with the exception that a table is always read after all tables it is dependent on. If there is a circular dependence then MySQL will issue an error.
All standard WHERE optimizations are done.
If there is a row in A that matches the WHERE clause, but there wasn’t any row in B that matched the LEFT JOIN condition, then an extra B row is generated with all columns set to NULL.
If you use LEFT JOIN to find rows that don’t exist in some table and you have the following test: column_name IS NULL in the WHERE part, where column_name is a column that is declared as NOT NULL, then MySQL will stop searching after more rows (for a particular key combination) after it has found one row that matches the LEFT JOIN condition.
RIGHT JOIN is implemented analogously as LEFT JOIN.
The table read order forced by LEFT JOIN and STRAIGHT JOIN will help the join optimizer (which calculates in which order tables should be joined) to do its work much more quickly, as there are fewer table permutations to check.
Note that the above means that if you do a query of type:
SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key
MySQL will do a full scan on b as the LEFT JOIN will force it to be read before d.
The fix in this case is to change the query to:
SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key
44:Joins in MYSQL
“JOIN” is a SQL keyword used to query data from two or more related tables.
To very simple example would be users (students) and course enrollments:
‘user’ table:
id name course
1 Alice 1
2 Bob 1
3 Caroline 2
4 David 5
5 Emma (NULL)
‘course’ table:
id name
1 HTML5
2 CSS3
3 JavaScript
4 PHP
5 MySQL
INNER JOIN (or just JOIN)
The most frequently used clause is INNER JOIN. This produces a set of records which match in both the user and course tables, i.e. all users who are enrolled on a course:

Query
SELECT user.name, course.name
FROM `user`
INNER JOIN `course` on user.course = course.id;
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
LEFT JOIN
What if we require a list of all students and their courses even if they’re not enrolled on one? A LEFT JOIN produces a set of records which matches every entry in the left table (user) regardless of any matching entry in the right table (course):
Query
SELECT user.name, course.name
FROM `user`
LEFT JOIN `course` on user.course = course.id;
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
Emma (NULL)
RIGHT JOIN
Perhaps we require a list all courses and students even if no one has been enrolled? A RIGHT JOIN produces a set of records which matches every entry in the right table (course) regardless of any matching entry in the left table (user):

Query
SELECT user.name, course.name
FROM `user`
RIGHT JOIN `course` on user.course = course.id;
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
(NULL) JavaScript
(NULL) PHP
David MySQL
OUTER JOIN (or FULL OUTER JOIN)
Our last option is the OUTER JOIN which returns all records in both tables regardless of any match. Where no match exists, the missing side will contain NULL.
OUTER JOIN is less useful than INNER, LEFT or RIGHT and it’s not implemented in MySQL. However, you can work around this restriction using the UNION of a LEFT and RIGHT JOIN, e.g.

Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
Emma (NULL)
(NULL) JavaScript
(NULL) PHP
45:Stored procedure in MYSQL

Stored procedures are set of SQL commands that are stored in the database data server. After the storing of the commands is done, the tasks can be performed or executed continuously, without being repeatedly sent to the server. This also helps in decreasing the traffic.
There are many advantages of using stored procedures, which include:
* The functionality is application and platform related.
* Functionality has to be developed only once, and all applications can call the same commands.
* Task execution becomes easier and less complicated.
* Network Traffic reduced to a greater extent.
* Centralization of all commands made possible, which is helpful for various applications that repeatedly call the same set of complicated commands.
* Runs on any kind of environment.
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
routine_body:
Valid SQL procedure statement
Application
MySQL Stored Procedures can be applied in absolutely any place. Right from complex applications to simple procedures, these stored procedures can be utilized in absolutely any place.
Few of the many places that MySQL Stored procedures can be used are:
* When diverse client applications are structured using various languages in different platforms.
* When security is of highest importance, like in financial institutions, the users and applications would have no direct access to the database tables. This provides excellent secured environment.
* When very few database servers service the client machines, thereby providing efficient performance.
Though not as mature as Oracle, DB2 or the SQL Server, the MySQL Stored Procedures is definitely worth a try. If the structure of the database is the same, the same stored procedures can be used for all.
A simple example for MySQL Stored Procedure
To calculate the area of a circle with given radius R, the following commands can be given
delimiter //
create function Area (R double) returns double
deterministic
begin
declare A double;
set A = R * R * pi();
return A;
end
//
delimiter ;
And to call it from php code to display the area of a circle with radius 22cm,
$rs_area = mysql_query(“select Area(22)”);
$area = mysql_result($rs_area,0,0);
echo “The area of the circle with radius 22cm is ”.$area.” sq.cm”;
?>

46: What is a Trigger in MySQL Define different types of Trigger?

A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
A trigger is associated with a table and is defined to activate when an INSERT, DELETE, or UPDATE statement for the table executes. A trigger can be set to activate either before or after the triggering statement. For example, you can have a trigger activate before each row that is deleted from a table or after each row that is updated.
An example of the MySQL triggers usage can be found below:
* First we will create the table for which the trigger will be set.
mysql> CREATE TABLE people (age INT, name varchar(150));
* Next we will define the trigger. It will be executed before every INSERT statement for the people table.
mysql> delimiter //
mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age < 0 THEN SET NEW.age = 0; END IF;//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
* We will insert two records to check the trigger functionality.
mysql> INSERT INTO people VALUES (-20, 'Sid'), (30, 'Josh');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
* At the end we will check the result.
mysql> SELECT * FROM people;
+-------+-------+
| age | name |
+-------+-------+
| 0 | Sid |
| 30 | Josh |
+-------+-------+
2 rows in set (0.00 sec)
47:WHAT IS A VIEW?

A view is a pre-compiled virtual table that is generated by a user-defined SELECT statement. Unlike tables, views don't physically store data on the database server, instead they act as aliases to existing tables.
WHY USE VIEWS?
Views are used to customize the data that gets returned from a SELECT query.
BEFORE WE BEGIN
The following CREATE TABLE queries should be executed on a test database, if you plan to follow along with my examples:
CREATE TABLE NewsCategories
( catID int not null auto_increment, catName varchar(32), primary key(catID));
CREATE TABLE News
( newsID int not null auto_increment, catID int not null, title
varchar(32) not null, txt blob, primary key(newsID));
INSERT INTO NewsCategories (catName) VALUES ('Main');
INSERT INTO News (catID, title, txt) VALUES (1, 'My Article!', 'Hello World');
CREATING A VIEW
Views are relatively easy to use. The syntax for creating a view is:
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
The following command will create a simple view that pulls the title and txt field from the News table:
CREATE VIEW newsView AS SELECT title, txt FROM News;
To see your view in action all you will need to do is run a normal SELECT statement against the view (instead of a table). The following query will run the view you just created, which will select all title and txt fields from the News table.
SELECT * FROM newsView
To create a view with MySQL Query Browser, simply right click on the database (in the right column) and click Create New View. Enter a view name and click Create View. You will then be presented with a code template for creating a view.
MODIFYING A VIEW
To get a list of views, you can use the SHOW TABLES command. Here is a SHOW TABLES query that will display only views and filter out tables:
SHOW FULL TABLES WHERE Table_type='VIEW'
To see the code behind the view, run:
SHOW CREATE VIEW newsView
The code it returns will probably be slightly different than the code you created, but it should do the same thing. It will include all of the optional CREATE VIEW attributes, which you didn't include in the example above. You should be able to copy and paste the code and change the CREATE VIEW to ALTER VIEW. Let's also JOIN the NewsCategories table so that we can see the CatName each news record is associated with, while SELECTing from our view. So it should look something like this:
ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `newsview` AS
SELECT n.newsID, n.catID, n.title, n.txt, c.catName FROM News AS n JOIN NewsCategories AS c ON c.catID=n.catID
You can easily create and modify views using the Query Browser tool. If you're using the latest version of MySQL Query Browser, you should see your view listed along with your tables under your selected database in the right column. If this is the case, you can right click on the View and click Edit View.

php interview questions and answers

1:What is the value of $b in the following code?
$a="5 USD";
$b=10+$a;
echo $b;
?>

Ans:15

2:What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods?
In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc.In the post method the data will be available as data blocks and not as query string.

3:What is GPC?
G – Get
P – Post
C – Cookies

4:What are super global arrays?

All variables that come into PHP arrive inside one of several special arrays known collectively as the superglobals. They're called superglobal because they are available everywhere in your script, even inside classes and functions.

5:Give some example for super global arrays?

$GLOBALS
$_GET
$_POST
$_SESSION
$_COOKIE
$_REQUEST
$_ENV
$_SERVER

6:What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?

MOVE_UPLOAD_FILE : This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
Copy :Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

7:When I do the following, the output is printed in the wrong order:

function myfunc($argument) {
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);

What's going on?
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the
value, not echo it.

8:What are the Formatting and Printing Strings available in PHP?

Function Description
printf() : Displays a formatted string
sprintf() : Saves a formatted string in a variable
fprintf() : Prints a formatted string to a file
number_format() : Formats numbers as strings

9:Explain the types of string comparision function in PHP.

Function Descriptions
strcmp() :Compares two strings (case sensitive)
strcasecmp() :Compares two strings (not case sensitive)
strnatcmp(str1, str2) :Compares two strings in ASCII order, but
any numbers are compared numerically
strnatcasecmp(str1, str2):Compares two strings in ASCII order,
case insensitive, numbers as numbers
strncasecomp() : Compares two strings (not case sensitive)
and allows you to specify how many characters
to compare
strspn() : Compares a string against characters represented
by a mask
strcspn() : Compares a string that contains characters not in
the mask

10:Explain soundex() and metaphone().

soundex()
The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. he soundex() function can be used for spelling applications.
$str = "hello";
echo soundex($str);
?>
metaphone()
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications.
echo metaphone("world");
?>
11:What do you mean range()?

Starting from a low value and going to a high value, the range() function creates an array of consecutive integer or character values. It takes up to three arguments: a starting value, an ending value, and an increment value. If only two arguments are given, the increment value defaults to 1.
Example :
echo range(1,10); // Returns 1,2,3,4,5,6,7,8,9,10
?>
12:How to read and display a HTML source from the website url?

$filename="http://www.kaptivate.in/";
$fh=fopen("$filename", "r");
while( !feof($fh) ){
$contents=htmlspecialchars(fgets($fh, 1024));
print "
$contents
";
}
fclose($fh);
?>
13:What is properties of class?

Class member variables are called "properties". We may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

14:How to use HTTP Headers inside PHP? Write the statement through which it can be added?

HTTP headers can be used in PHP by redirection which is written as:
The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.

15:Why we used PHP?

Because of several main reason we have to use PHP. These are:
1.PHP runs on many different platforms like that Unix,Linux and Windows etc.
2.It codes and software are free and easy to download.
3.It is secure because user can only aware about output doesn't know how that comes.
4.It is fast,flexible and reliable.
5.It supports many servers like: Apache,IIS etc.

16:Arrays in PHP?

Create array in PHP to solved out the problem of writing same variable name many time.In this we create a array of variable name and enter the similar variables in terms of element.Each element in array has a unique key.Using that key we can easily access the wanted element.Arrays are essential for storing, managing and operating on sets of variables effectively. Array are of three types:
1.Numeric array
2.Associative array
3.Multidimensional array
Numeric array is used to create an array with a unique key.Associative array is used to create an array where each unique key is associated with their value.Multidimensional array is used when we declare multiple arrays in an array.

17:What is foreach loop in php?

foreach:Uses, When When we want execute a block of code for each element in an array.
Syntax:
foreach (array as value)
{
code will be executed;
}
eg:
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "
";
}
?>
18:How we used $_get and $_post variable in PHP?

We know that when we use $_GET variable all data_values are display on our URL.So,using this we don't have to send secret data (Like:password, account code).But using we can bookmarked the importpage.
We use $_POST variable when we want to send data_values without display on URL.And their is no limit to send particular amount of character.
Using this we can not bookmarked the page.

19:Why we use $_REQUEST variable?

We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable.
Example:
R4R Welcomes You .

You are years old!

20:How we handle errors in PHP?Explain it?


In PHP we can handle errors easily.Because when error comes it gives error line with their respective line and send error message to the web browser.
When we creating any web application and scripts. We should handle errors wisely.Because when this not handle properly it can make bg hole in security.
In PHP we handle errors by using these methods:
1.Simple "die()" statements
2.Custom errors and error triggers
3.Error reporting

21: How we use Custom errors and error triggers error handling method in PHP?

In Custom errors and error triggers,we handle errors by
using self made functions.
1.Custom errors : By using this can handle the multiple
errors that gives multiple message.
Syntax:
set_error_handler(\\\"Custom_Error\\\");
In this syntax if we want that our error handle, handle
only one error than we write only one argument otherwise
for handle multiple errors we can write multiple arguments.

Example:
//function made to handle errorfunction
custom_Error($errorno, $errorstr)
{
echo \\\"Error: [$errorno] $errorstr\\\"; }
//set error handler like that
set_error_handler(\\\"custom_Error\\\");
//trigger to that error
echo($verify);?>

2.error trigger : In PHP we use error trigger to handle
those kind of error when user enter some input data.If
data has an error than handle by error trigger function.
Syntax:

$i=0;if ($i<=1)
{
trigger_error(\\\"I should be greater than 1 \\\");
}
?>
In this trigger_error function generate error when i is
less than or greater than 1.

22:What do you understand about Exception Handling in PHP?

In PHP 5 we introduce a Exception handle to handle run time exception.It is used to change the normal flow of the code execution if a specified error condition occurs.
An exception can be thrown, and caught("catched") within PHP. Write code in try block,Each try must have at least one catch block. Multiple catch blocks can be used to catch different classes of exceptions.
Some error handler methods given below:
1.Basic use of Exceptions
2.Creating a custom exception handler
3.Multiple exceptions
4.Re-throwing an exception
5.Setting a top level exception handler

23: What is the difference b/n 'action' and 'target' in form tag?

Action:
Action attribute specifies where to send the form-data when
a form is submitted.
Syntax:
Example:
action="formValidation.php">
Target:
The target attribute specifies where to open the action URL.
Syntax:
Value:
_blank – open in new window
_self- Open in the same frame as it was clicked
_parent- Open in the parent frameset
_top- Open in the full body of the window
Framename- Open in a named frame

24:What do you understand about PHP accelerator ?

Basically PHP accelerator is used to boost up the performance of PHP programing language.We use PHP accelerator to reduce the server load and also use to enhance the performance of PHP code near about 2-10 times.In one word we can say that PHP accelertator is code optimization technique.

25: What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where
mysql_fetch_array will collect all matching records from the table in an
array

26:How we use ceil() and floor() function in PHP?

ceil() is use to find nearest maximum values of passing value.
Example:
$var=6.5;
$ans_var=ceil($var);
echo $ans_var;
Output:
7
floor() is use to find nearest minimum values of passing value.
Example:
$var=6.5
$ans_var=floor($var);
echo $ans_var;
Output:
6

27:What is the answer of following code

echo 1< 2 and echo 1 >2 ?

Output of the given code are given below:
echo 1<2
output: 1
echo 1>2
output: no output

28: What is the difference b/w isset and empty?

The main difference b/w isset and empty are given below:
isset: This variable is used to handle functions and checked a variable is set even through it is empty.
empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.