Thursday, 20 July 2017

OOPS interview questions and answers in php


1
.What is Polymorphism ?

Ans: Polymorphism means the ability to have many forms.The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they're all used the same way
        
There are two types of Polymorphism; they are: 
  1. Compile time (function overloading) or static polymorphism
  2. Run time (function overriding) or dynamic polymorphism
Usually the  PHP "does not support" compile time polymorphism as per Native langues but by using some special cases we can achieve Static polymorphism , 
 Ref:- http://swapnilg.com/overloading-php-example

2.What is function overloading and give an example in php?
 Ans: Function overloading is the ability to create multiple functions of the same name with different implementations.Function overloading in PHP is used to dynamically create properties and methods. These dynamic entities are processed by magic methods which can be used in a class for various action types. Function overloading contains same function name and that function preforms different task according to number of arguments.
 Types of Overloading in PHP: There are two types of overloading in PHP.
  • Property Overloading
  • Method Overloading
  We can achieve property overloading using below methods. 
  • _set(): triggered while initializing overloaded properties.
  • __get(): triggered while using overloaded properties with PHP print statements.
  • __isset(): This magic method is invoked when we check overloaded properties with isset() function
  • __unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties.
   Ex:
  
<?php
class GFG { 
// Location of overloading data 
private $data = array(); 
// Overloading not used here 
public $declared = 1; 
// Overloading used when accessed 
// outside the class 
private $hidden = 2; 
// Function definition 
public function __set($name, $value) { 
echo "Setting '$name' to '$value'\n"; 
$this->data[$name] = $value; 
// Function definition 
public function __get($name) { 
echo "Getting '$name: "; 
if (array_key_exists($name, $this->data)) { 
return $this->data[$name]; 
$trace = debug_backtrace(); 
return null; 
// Function definition 
public function __isset($name) { 
echo "Is '$name' set?\n"; 
return isset($this->data[$name]); 
// Definition of __unset function 
public function __unset($name) { 
echo "Unsetting '$name'\n"; 
unset($this->data[$name]); 
// getHidden functino definition 
public function getHidden() { 
return $this->hidden; 
// Create an object 
$obj = new GFG; 
// Set value 1 to the object variable 
$obj->a = 1; 
echo $obj->a . "\n"; 
// Use isset function to check 
// 'a' is set or not 
var_dump(isset($obj->a)); 
// Unset 'a' 
unset($obj->a); 
var_dump(isset($obj->a)); 
echo $obj->declared . "\n\n"; 
echo "Private property are visible inside the class "; 
echo $obj->getHidden() . "\n\n"; 

echo "Private property are not visible outside of class\n"; 
echo $obj->hidden . "\n"; 

?> 
Out Put :
       Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1

Private property are visible inside the class 2

Private property are not visible outside of class
Getting 'hidden:
 
Method Overloading: It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context.
The related magic functions are,
  • __call() – triggered while invoking overloaded methods in the object context.
  • __callStatic() – triggered while invoking overloaded methods in static context.
EX :-    
 <?php 
class GFG { 
public function __call($name, $arguments) { 
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n"; 
public static function __callStatic($name, $arguments) { 
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n"; 
// Create new object 
$obj = new GFG; 
$obj->runTest('in object context'); 
GFG::runTest('in static context'); 
?> 
Output:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context

3. Can you  call parent class constructor using clild class object ?


An
Parent constructors are not called implicitly if the child class defines a constructor. 
In order to run a parent constructor, a call to parent::__construct() within
 the child constructor is required.

ex :  
abstract class view
{
 public $vieverid;

 function __construct($viewerid) {
  $this->viewer = $viewerid;
 }
}
class viewactor extends view{

 function __construct($viewerid) {
  parent::__construct($viewerid); // manual call
  // do your stuff here...
  $this->viewerid = $viewerid;
 }

3.Interface Vs abstract class ?

Image result


Abstrsct Class Properties 


Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
5.Abstract Class is not possible to implement multiple inheritance.
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class

  Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.
interface MyInterface{
    public function foo();
    public function bar();
}

abstract class MyAbstract1{
    abstract public function baz();
}


abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
    public function foo(){ echo "foo"; }
    public function bar(){ echo "bar"; }
    public function baz(){ echo "baz"; }
}

class MyClass extends MyAbstract2{
}

$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz
Can not instantiate abstract class: Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract.
Example below :
abstract class AbstractClass
{

    abstract protected function getValue();
    abstract protected function prefixValue($prefix);


    public function printOut() {
        echo "Hello how are you?";
    }
}

$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass
Ref : http://www.developer.com/lang/php/article.php/10941_3604111_2/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm

4. What is Data Abstraction ?
ANS : Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.

5.What is 
Encapsulation ?

ANS:
          Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class. In simpler words, attributes of the class are kept private and public getter and setter methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.
More Details ; http://www.csharpstar.com/top-30-oops-interview-questions/

Monday, 17 July 2017

Mysql Interview Questions




1.What is Difference between MYISAM and INNODB ?

ANS :

 MYISM

INNODB

1.      MYISAM supports Table-level Locking

1.      InnoDB supports Row-level Locking

2.      MyISAM designed for need of speed

2.      InnoDB designed for maximum performance when processing high volume of data

3.      MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS

3.      InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS

4.      MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)

4.      InnoDB stores its tables and indexes in a tablespace

5.      MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.

5.InnoDB supports transaction. You can commit and rollback with InnoDB

6.      MYISAM supports fulltext search

6.InnoDB supports Fulltext index search

7.      You can use MyISAM, if the table is more static with lots of select and less update and delete.


7.you can use InnoDB for DML operation.

2. Give me an example for IF and case conditions in mysql?

Ans:
       
  
 UPDATE  cscart_users SET  is_root = IF(is_root = 'Y','N','Y')

   UPDATE  
cscart_users SET  is_root =  CASE WHEN is_root = 'N' THEN 'Y' ELSE 'N' END 

3.Create dummy table structure.

     CREATE TABLE new_table LIKE old_table;  

 4. Move  distinct values Data from one table to another table

      INSERT INTO new_table SELECT * FROM old_table;

5. Transfer data from one table to another new table

   create table new_table select * from oldtable group by zip     
6. What is default port for MSQL server ? The default port for MySQL Server is 3306. Another standard default is port 1433 in TCP/IP for SQL Server. 

7. What do DDL, DML, and DCL stand for? DDL is the abbreviation for Data Definition Language dealing with database schemas as well as the description of how data resides in the database. An example is CREATE TABLE command. DML denotes Data Manipulation Language such as SELECT, INSERT etc. DCL stands for Data Control Language and includes commands like GRANT, REVOKE etc.8. What are meant by Joins in MySQL?

    
In MySQL the Joins are used to query data from two or more tables. The query is made using relationship between certain columns existing in the table. There are four types of Joins in MySQL. Inner Join returns the rows if there is at least one match in both the tables. Left Join returns all the rows form the left table even if there is no match in the right table. Right Join returns all the rows from the right table even if no matches exist in left table. Full Join would return rows when there is at least one match in the tables.

9
.What are the limits for using columns to create the Index?

      Different types of strings that can be used for database columns are SET, BLOB, VARCHAR, TEX, ENUM, and CHAR.

10.What is the difference between a candidate key and a primary key?

      There can be multiple Candidate keys in a table in relation database e.g. Oracle, MySQL, Sybase or MSSQL but only one primary key is permitted.

  An example of Primary key and Candidate key can be ID and SSN number(
Social Security number) in a Employee table, Since both can identify each employee uniquely they are candidate key and any one can become primary key. Now if you have to choose between them as primary key, I will go ID as primary key because SSN is sensitive information and may not be allow/not safe to use as String in queries as frequently as ID. Second reason of choosing ID over SSN as primary key can be use of ID as primary tracking ID within organization and its frequent use all over the place. Once you choose a primary key, All candidate key are like unique keys.

11.What are the TRIGGERS that can be used in MySQL tables? 

     •    BEFORE INSERT

·         AFTER INSERT

·         BEFORE UPDATE

·        AFTER UPDATE

·          BEFORE DELETE

·          AFTER DELETE

  Ex: 

create trigger update_customer  //Trigger Name  

 before update on customer   
 
for each row        //Before update on parent
  begin
      insert into mini_statement values (new.acc_no, new.avail_balance)  
 
end

 

12. What is the difference between FLOAT and DOUBLE?

FLOAT stores floating point numbers with accuracy up to 8 places and allocates 4 bytes, on the other hand DOUBLE stores floating point numbers with accuracy up to 18 places and allocates 8 bytes.

 13.What is the difference between CHAR and VARCHAR?

  1. CHAR and VARCHAR are differ in storage and retrieval.
  2. CHAR column length is fixed while VARCHAR length is variable.
  3. The maximum no. of character CHAR data type can hold is 255 character while VARCHAR can hold up to 4000 character.
  4. CHAR is 50% faster than VARCHAR.
  5. CHAR uses static memory allocation while VARCHAR uses dynamic memory allocation.

14.What is the difference between MySQL_connect and MySQL_pconnect?

Mysql_connect:

  1. It opens a new connection to the database.
  2. Every time you need to open and close database connection, depending on the request.
  3. Opens page every time when it loaded.

Mysql_pconnect:

  1. In Mysql_pconnect, "p" stands for persistent connection so it opens the persistent connection.
  2. the database connection can not be closed.
  3. it is more useful if your site has more traffic because there is no need to open and close connection frequently and every time when page is loaded.

15.What does " i_am_a_dummy flag" do in MySQL?

The " i_am_a_dummy flag" enables MySQL engine to refuse any UPDATE or DELETE statement to execute if the WHERE clause is not present.

16.How to get the current date in MySQL?

select CURRENT_DATE();

17.How to change a password for an existing user via Mysqladmin?

 Mysqladmin -u root -p password "newpassword".

 18.How to display Nth highest salary from a table in a MySQL query?

 select distinct(salary) from employee order by salary desc limit n-1,1  
   (OR)
SELECT DISTINCT salary

FROM   employees e1
WHERE  1 = (SELECT Count(DISTINCT salary)
            FROM   employees e2
            WHERE  e2.salary > e1.salary)
ORDER  BY salary DESC;

19.How many columns can you create for an index?
You can create maximum of 16 indexed columns for a standard table.

20.
What is the usage of ENUMs in MySQL?

 ENUM is a string object used to specify set of predefined values and that can be used during table creation.

exp: Create table size(name ENUM('SUNDAY', 'MONDAY','TUESDAY');

 21.What is View and give me an example ?


A view is a virtual table which consists of a subset of data contained in a table. Views are not virtually present, and it takes less space to store. View can have data of one or more tables combined, and it is depending on the relationship.

ex :

CREATE VIEW [VeiwNameAS
SELECT ProductID, ProductName
FROM Products
WHERE Discontinued = No; 

22.What is An Index ?

 An index is performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and it will be faster to retrieve data.

Index architectures are classified as clustered or non-clustered. Clustered indexes are indexes whose order of the rows in the data pages corresponds to the order of the rows in the index. This order is why only one clustered index can exist in any table, whereas, many non-clustered indexes can exist in the table.


 A clustered index is a type of index where the table records are physically re-ordered to match the index. A nonclustered index, on the other hand, is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk.


23. How to get json object in mysql ?


SELECT json_object('name', name, 'phone', phone)  FROM person;

 24. How to import mysql database using comand prompt ?

C:\xampp\mysql\bin>mysql -u username -ppassword databasename < C:\file.sql

25. What is difference between union and join ? 
A.  


A join connects tables horizontally: take the data from table A and add the columns from table B, on a row-by-row basis. For example, you might join Customer to Orders on the basis of CustomerID to get the name of each customer and the date of each order they've placed.

A union stacks the rows of two tables, vertically: take the data from table A and add rows from table B. This works when the fields are similar. For example, if you move old orders to an archive table periodically to keep your main Orders table short, you might run a UNION against the two tablets to get lifetime sales.

This applies equally for all common databases; MySQL is not unusual in its use of these two commands.

26. What is unionall in mysql ?
Ans:
Union All Returns the duplicate values also. But union returns distinct values from two tables.

27. What is difference between functions and procedures ?


Ans: 

 

S.No

Functions

Procedures

1

Function is compiled and executed every time it is called

Procedure is compiled once and executed every time it is called

2

The functions always returns an value

Procedures need not to return an value but it can return 1 or n value

3

Functions have input parameters

Procedures have input and out put parameters

4

Functions called by procedures

Procedures can’t call from functions

5

You can’t use try catch blocks in functions

You can use try catch blocks in procedures

6

We can use functions in select query

We cant use procedure in select query.

7

Functions only allows select statements.

Procedure can allow DML statements and as well select statements also

8

 Ex: 
crate function Num_Of_Years(date1 datereturn int Deterministic 

begin 
    declare date2 date;

    select current_date() into date2;

    return year(date2)-year(date1);
end;

//Calling functions 
select emp_id,first_name,Num_Of_Years(start_date) as 'years' from employee 

Ex: 

CREATE PROCEDURE country_hos

(IN con CHAR(20))

BEGIN

  SELECT Name, HeadOfState FROM Country

  WHERE Continent = con;

END

 // Call Stored Procedure

CALL country_hos('Europe');

     
28. What is difference between distinct and group by ?
Ans: 
GROUP BY lets you use aggregate functions, like AVGMAXMINSUM, and COUNT. On the other hand DISTINCT just removes duplicates.

    SELECT name, SUM(transaction) FROM myTbl GROUP BY name
    SELECT name, Distinct(SALARY)  from Employee 

29
Difference between Having clause and Group by clause
  
Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. 

SELECT COUNT
(SALARIES) AS COUNT_SALARIES, EMPLOYEES FROM EMPLOYEES GROUP BY SALARIES HAVING COUNT(SALARIES) > 1; 

  

S.No.

Having Clause

GroupBy Clause

1.It is used for applying some extra condition to the query.The groupby clause is used to group the data according to particular column or row.
2.Having cannot be used without groupby clause.groupby can be used without having clause with the select statement.
3.The having clause can contain aggregate functions.It cannot contain aggregate functions.
4.It restrict the query output by using some conditionsIt groups the output on basis of some rows or columns.

 30 . How to add index/primary key to existing table ?

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)
ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)

31. How modify existing column datatype ?

ALTER TABLE employee ADD FirstName  VARCHAR(255);
ALTER TABLE employee MODIFY COLUMN FirstName VARCHAR(255);

32. How to change existing column name?

MySQL <=8
 ALTER TABLE table_names CHANGE `old_column_name` `new_column_name` varchar(50);
MySQL 8
 ALTER TABLE table_name RENAME COLUMN `old_col_name` TO `new_col_name`;

33. B RIGHT JOIN A, A LEFTJOIN B. Is it both statements give same result?

Ans: Yes both statements give same Results. Here A table is main table for 
both the statements

34. Write MySQL command to update a table with certain values but with

an extra condition: if the row to update is not found you need to create

a new entry.


35. What is cursor?

Ans: A cursor is a database object that allows you to retrieve and manipulate rows 
from a result set one at a time.
36. What are differences between MySQL Vs PostgreSQL Vs SQL Server

 http://pasteboard.co/c19l4Vgl9H8h.png

36. How to get department wise first two maximum salary's ?

ANS: PostGresSQL:
WITH RankedSalaries AS (
    SELECT
        e.EmployeeName,
        d.DepartmentName,
        e.Salary,
        RANK() OVER (
            PARTITION BY d.DepartmentID ORDER BY e.Salary DESC
        ) AS SalaryRank
    FROM employee e
    INNER JOIN department d ON e.DepartmentID = d.DepartmentID
)
SELECT DepartmentName, EmployeeName, Salary
FROM RankedSalaries
WHERE SalaryRank <= 2;

Mysql:

SELECT department_name, employee_name, salary FROM ( SELECT d.name as department_name, e.firstname as employee_name, e.salary, ROW_NUMBER() OVER ( PARTITION BY e.DepartmentId ORDER BY e.salary DESC ) AS salary_rank FROM employee e INNER JOIN department d ON e.DepartmentId = d.id ) AS ranked_salaries WHERE salary_rank <= 2