Top Interview Questions and Answers

Top Interview Questions and Answers
Interview Sortout

Browsing "Older Posts"

Browsing Category "PHP"

What is New In CodeIgniter 4.x?

By Dhananjay → December 4, 2018

80 PHP functions asked in any Interview

By Dhananjay → September 11, 2018
This post contains the list of PHP functions that are frequently asked in various interview from freshers as well as experienced candidates. These are the parts of basic and core PHP. One must be familiar with these functions, I have just mentioned the definition in one line for each functions.They are frequently used in our application. Hope you will find this helpful.
  1. strlen() : returns the length of string passed.
  2. stristr() : returns rest of the string after the first occurence of a string in another string.
  3. stripos() : find the position of the first occurence of the string in another string.
  4. strip_tags() : returns string from html tags.
  5. strchr() : find first occurence of a string in another string and returns rest of the string.
  6. str_word_count() : returnd number of words in a string.
  7. str_split() : returns an array of charecters that string contains, when passed to it.
  8. str_replace() : search and replace a substring in a string by another substring.
  9. str_pad() : provide a virtual length to a string. It adds desired charecter to a string to make it up to required length.
  10. str_repeat() : Return a repeated string by a number of times.
  11. str_getcsv() : Parse a string to get the fields for CSV.
  12. rtrim() : remove white spaces from a string from right side.
  13. ord() : When we need to find ASCII value of the first charecter of the string we use ord().
  14. nl2br() : Conver all the new line charecters to BR tag of HTML.
  15. strstr() : returns rest of the string after the first occurence of a string in another string, find only case sensitive string.
  16. strtok() : breaks a strings into substrings
  17. strtoupper() : convert the case of string into uppercase.
  18. strtolower() : convert the case of string into lowercase.
  19. substr() : return a substring from a string of a length and from starting position.
  20. trim() : removes the white spaces from a string from left and right.
  21. ucfirst() : convert the case of first letters of all words in a string to uppercase.
  22. wordwrap() : break lines after a length.
  23. print() : output the result string when passed to it.
  24. print_r() : prints a resources ,object or an array along with the indexes.
  25. unlink() : delete a file from its location.
  26. unset() : set the value of a variable undefined.
  27. isset() : check whether the variable is defined or not.
  28. empty() : check whether an array is empty.
  29. array_chunk() : breaks an array into chunks of small arrays.
  30. array_combine() : combine two arrays of equal size where one is used for keys and another one is used for values.
  31. array_count_values() : count and returns the number of values of an array
  32. array_diff() : returns an array having difference between two arrays.
  33. array_flip() : flip key and value simultaneously.
  34. array_filter() : filter the values of an array based on a callback function.
  35. array_key_exists() : returns true if a key exists in an array.
  36. array_keys() : returns the array of keys from an array.
  37. array_map() : apply some operation on each value of an array and return a new array with modified values.
  38. array_merge() : merge the values of two array while retaining their keys.
  39. array_merge_recursive() : merge multidimensional arrays.
  40. array_push() : add a new value in an array at the end.
  41. array_rand() : select some random keys from an array.
  42. array_replace() : replace values in an array from the values in another array.
  43. array_reverse() : reverse the order of array and return new array.
  44. array_search() : search a value in an array and return the key of the value.
  45. array_shift() : remove the first element in an array.
  46. array_sum() : sum up all the values in an array.
  47. array_unique() : remove all the replicated values in an array.
  48. array_values() : returns an array of values with numeric index.
  49. array_walk() : Go to each value and run over an user defined function.
  50. array_walk_recursive() : Does the same recursively for an array.
  51. compact() : The compact() function creates an array from variables and their values.
  52. asort() : Sort an array values in ascending order.
  53. arsort() : Sort an array values in descending order.
  54. in_array() : returns true if a value find in an array.
  55. key() : return the key from the current pointer position.
  56. krsort() : sort and array based on keys and in descending order.
  57. ksort() : sort and array based on keys and in ascending order.
  58. range() : create an array from the range passed to it.
  59. date_create() : create a new dateTime object.
  60. date_create_from_format() : Create a user defined date from given format.
  61. date_diff() : returns difference between two dates.
  62. date_sub() : suntracts some period of time from a given date.
  63. date() : output the current date and time based on parameters given to it.
  64. gettimeofday() : output current time.
  65. gmmktime() : output UNIX time for GMT.
  66. localtime() : returns local time as UNIX timestamp.
  67. strtotime() : convert a string having datetime information into UNIX date.
  68. time() : eturn the current time.
  69. ceil() : returns the next interger value of the floating number passed to it.
  70. floor(): returns the next lowest integer value
  71. abs() : returns the absolute value passed to it.
  72. base_convert() : convert the base of number system.
  73. is_nan() : check whether a value is Not a Number.
  74. is_infinite() : check wherther a value is Infine.
  75. max() : find the max value from an array.
  76. min() : find minimum value from an array.
  77. mt_rand() : based on Mersenne Twister algorithm creates a random number.
  78. rand() : generate a random number
  79. round() : returns a floating point number up to a particular place of decimal point.
  80. sqrt() : returns the square root of the value passed to it.

Hooks in CodeIgniter

By Dhananjay →

Hooks in CodeIgniter

In code igniter hooks are the points before and after the execution where we can call some specific functions. These functions are called hooks and points where we call hooks are called hook point. Hooks are usefull when we have to make some changes throught the application , then we can do this without hacking all the files, just adding one hook at appropriate point. We can modify the way of usual rendering in code igniter application. So hooks facilitates modification in functionality without changing the core.

How we can use a hook in code igniter framework?
Before we use any hook in application we need to enable the hook in config.php file.Set the enable_hook config variable : TRUE,

$config['enable_hooks'] = TRUE;


The framework provide number of Hook Points to ease the development and modification in application:

[1]pre_system:
The pre_system is called very early during system execution. Only the benchmark and hooks class have been loaded at this point.

[2]pre_controller:
As per the name just called before any of your controllers being called. When all the base classes are loaded, routing and security checks are done a pre_controller hook is called.

[3]post_controller_constructor:
The hook is called just after the controller class instantiated but none of the method is called.


[4]post_controller:
Called immediately after your controller is fully executed.

[5]display_override:
We have the _display() function in our core and we use it to render our view on browser after execution of all programms.
display_override allow use to display our own content at desired places.

$this->CI => get_instance();
$this->CI->output->get_output();


[6]cache_override:
We can call our own function instead of _display_cache() function using the cache_override hook. We can define our own cache display mechanism.

[7]post_system:
At the end of the system execution when final rendering is done post_system is called.



Define a hook :
A hook is defined in the hooks.php file located at application/config

Example for define a pre_controller hook:

$hook['pre_controller'] = array(  
            'class' => 'Classname',  
            'function' => 'functionname',  
            'filename' => 'filename.php',  
            'filepath' => 'hooks',  
            'params' => array('element1', 'element2', 'element3')  
            );  





CakePHP Advance : Most Common Interview Questions and Answers

By Dhananjay → September 6, 2018
cakephp

What is HMAC?
HMAC means Hash-based Message Authentication Code . This is a authentication code used with combination of an encryption key and a hash function.


What is Asset.cacheTime ?
Asset.cacheTime sets the asset cache time. This determines the http header Cache-Control’s max-age, and the http header’s Expire’s time for assets.


What is DSN?
DSN is Data Source Name. A connection string format that is formed like a URI. CakePHP supports DSN’s for Cache, Database, Log and Email connections.

What is PaaS?
Platform as a Service. Platform as a Service providers will provide cloud based hosting, database and caching resources. Some popular providers include Heroku, EngineYard and PagodaBox.

How we can use Cache in CakePHP?
Caching in CakePHP is facilitated by the Cache class. This class provides a static interface and uniform API to interact with various Caching implementations.


What types of Caching Engine does CakePHP provide?
1-FileCache-uses files.
2-ApcuEngine - uses the PHP APCu extension.
3-Wincache - uses the Wincache extension.
4-MemcachedEngine - uses the Memcached extension.
5-RedisEngine - uses the phpredis extension.


What is the default cache file path?
Path to where cache files should be saved. Defaults path is system's temp dir.

How to read a Cache Object in CakePHP?
Using Cache class we can read the object as given below:

$posts=Cache::read('posts');



How to write a Cache Object in CakePHP?
Using Cache class we can write the object as given below:

    Cache::write('posts',$posts);


How to remove an object completely from Cache?
Using Cache class we can delete the object as given below:

    Cache::delete('posts');


Can we read,write and delete multiple objects at a time?
Yes , we can do cache operations on multiple objects using functions like:

    Cache::deleteMany(['posts','comments','users']);
    Cache::readMany(['posts','comments','users']);
    Cache::writeMany(['posts'=>$posts,'comments'=>$comments,'users'=>$users]);


What is difference between Cache:clear() and Cache::delete() ?
Cache:clear() removes the values from associated with keys and empty them to hold new values, where as Cache:delete() removes the object completely from cache.

How can we disable or enable cache glaoblly in CakePHP?
We don't need to disable all Cache read & writes and to expiration. We can do this using enable() and disable():

    Cache::disable();
    Cache::enable();


What are the different log levels in CakePHP?
1-Emergency: system is unusable
2-Alert: action must be taken immediately
3-Critical: critical conditions
4-Error: error conditions
5-Warning: warning conditions
6-Notice: normal but significant condition
7-Info: informational messages
8-Debug: debug-level messages


What is CakeRequest?
CakeRequest is the default request object used in CakePHP. By default, CakeRequest is assigned to $this->request, and is available in Controllers, Views and Helpers.


What are different ways to access the parameters in CakePHP?
Following ways :

$this->request->controller;
$this->request['controller'];
$this->request->params['controller'];


How can we access the Passed Argumets from URI in CakePHP?
Way to access the Passed Argumets in CakePHP as:

$this->request->pass;
$this->request['pass'];
$this->request->params['pass'];


How can we access the Named Parameters from URI in CakePHP?
Way to access the Named Parameters in CakePHP as:

$this->request->named;
$this->request['named'];
$this->request->params['named'];


How can we read Query String Parameters?
We can read these paameters using Cake Request Handler :

  // url is as : /posts/index?page=1&sort=title
  $this->request->query['page'];


How can we detect the request type?
We can check any request as :
$this->request->is('post');
$this->request->is('get');
$this->request->is('ajax');
$this->request->is(['put','post']);


How to detect environment in CakePHP?
$this->request->addDetector(
    'post',
    array('env' => 'REQUEST_METHOD', 'value' => 'POST')
);


How to detect pattern value in CakePHP?
$this->request->addDetector(
    'iphone',
    array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i')
);


How to detect options in CakePHP?
$this->request->addDetector('internalIp', array(
    'env' => 'CLIENT_IP',
    'options' => array('192.168.0.101', '192.168.0.100')
));


How to detect callback in CakePHP?
$this->request->addDetector(
    'awesome',
    array('callback' => function ($request) {
        return isset($request->awesome);
    })
);



How to find the root directory of the the application?
$this->request->webroot;

How to find the base path in CakePHP?
$this->request->base;

How to find the full address of the current request in CakePHP?
$this->request->here;

CakePHP Advance Interview Questions and Answers For Experienced and Freshers

By Dhananjay → August 25, 2018

(1). What is the default cache Engine in CakePHP?
File Engine is the default cache Engine in Cake PHP.

(2). How many types of cache does CakePHP Support?
Different types of cache supported by CakePHP:
1-FileCache
2-ApcCache
3-Wincache
4-XcacheEngine
5-MemcacheEngine
6-RedisEngine

(3). How mamy types of Associations are there in CakePHP Models?
There are four association types in CakePHP:
Relationship Association type Example
one to one hasOne A user has one profile.
one to many hasMany A user can have multiple recipes.
many to one belongsTo Many recipes belong to a user.
many to many hasAndBelongsToMany Recipes have, and belong to, many ingredients.

(4). How to create association?
Model association example:
class Toy extends AppModel {
    public $hasOne = 'Profile';
    public $hasMany = array(
        'Toy' => array(
            'className' => 'Toy',
            'conditions' => array('Toy.approved' => '1'),
            'order' => 'Toy.created DESC'
        )
    );
}
?>

(5). How to create Pagination in List view?
Cake PHP has a built in component 'Paginator'. We can use this Component to create Pagination.

(6). How to destroy an association?
Use 'unbindModel' to destroy a particular type of association.
$this->Leader->unbindModel(
        array('hasMany' => array('Follower'))
    );


(7). Give an example of LEFT JOIN using CakePHP ORM?
LEFT JOIN example using cake php ORM:
$options['joins'] = array(
    array('table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);
$Item->find('all', $options);

(8). How to prevent the default View and Layout to be rendered?
We can set the default view and default Layout variable to false.
$this->layout='';
$this->autoRender = false;

(9). What is layout in CakePHP?
View files that contain presentational code that wraps many interfaces in your application. Most views are rendered inside a layout.

(10).  What Is A Component In Cakephp?
Components are packages shared between controllers. They are useful when a common logic or code is required between different controllers.

(11). What are Components Used in Cakephp?
1-Security
2-Sessions
3-Access control lists
4-Emails
5-Cookies
6-Authentication
7-Request handling
8-Scaffolding

(12). What Is A Behavior?
Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.

CakePHP Interview Questions and Answers

By Dhananjay → July 1, 2018

What is CakePHP ?
CakePHP is an open-source free web framework based on MVC pattern and written in PHP scripting Language for rapid web development.

What is MVC in CakePHP?
Model view controller (MVC) is an architectural pattern used in software engineering.
Model: Handle database related functionality, manipulating database related query like add, edit , delete.
View: Design parts written here (HTML+PHP)
Controller: Business Logic goes here

What are controllers?
A controller is used to manage the logic for a part of your application. Most commonly, controllers are used to manage the logic for a single model. Controllers can include any number of methods which are usually referred to as actions. Actions are controller methods used to display views. An action is a single method of a controller.


List some features of CakePHP framework ?
Top features of CakePHP framework
1-MVC Architecture
2-Zero configuration
3-Inbuilt validation
4-ACL Functionality and Security
5-CRUD scaffolding
6-Easily extendable with plug-ins
7-Quick and flexible


What are Hooks in CakePHP?
CakePHP hooks are callback functions that are called before or after a model operation and defined in models.
List of some Hooks functions provided by CakePHP.
1-beforeFind
2-afterFind
3-beforeValidate
4-afterValidate
5-beforeSave
6-afterSave
7-beforeDelete
8-afterDelete
9-onError


What is default function for a controller?
function index() is default function in controller.

What is a Element?
Element in cakephp are smaller and reusable bits of view code. Elements are usually rendered inside views.

What Is Scaffolding In Cakephp?
Scaffolding is a technical way that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

How To Get Current URL In CakePHP?
Simple using the following bit of code:
 
  $this->here;
 

How can you make urls search engine friendly while using cakephp?
It’s an automatic task that is done by cakephp.

How cakephp URL looks in address bar?
http://example.com/controller/action/param1/param2/param3

What is Composer? How to create a CakePHP Project using Composer?
Composer is a tool for managing project dependencies. You can create a CakePHP project using Composer by running below commands on terminal.

 
  php composer.phar create-project --prefer-dist cakephp/app my_app_name
 

How To Get Controller Name In CakePHP Views?
Get controller name in CakePHP:
 
  $this->request->params['controller'];
 


What is a Helper in CakePHP?
Helpers in CakePHP are associated with Presentation layers of application.Helpers mainly contain presentational logic which is available to share between many views, elements, or layouts.


What are are drawbacks of cakephp?.
The learning curve, and it loads full application before it starts your task. Its not recommended for small projects because of heavy structure.


What is the name of Cakephp database configuration file name and its location?
Default file name is database.php.default.
Its located in "/app/config/database.php.defaut"


What is habtm?
Has And Belongs To Many is a kind of associations that can be defined in models for retrieving associated data across different entities.

List some database related functions in cakephp.
find, findAll , findAllBy , findBy , findNeighbours and query.

Top 10 Codeigniter Interview Questions and Answers for Experienced

By Dhananjay → May 31, 2018


1- What is hook?
CodeIgniter’s Hooks feature modify the core functionalitis of the framework without changing the core files. For example, If you want to run a script right before your controllers get loaded, or right after or at any other location, you can use Hook.

2- How many types of hooks are there in Code Igniter?
There are 7 availabe hook points:

pre_system :
Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.

pre_controller :
Called prior to controllers being called. All base classes, routing, and security checks have been done.

post_controller_constructor:
Called after controller is instantiated, but prior to any method calls happening.

post_controller:
Called after the controller is executed.

display_override:
Overrides the _display() method, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI->get_instance() and then the finalized data will be available by calling $this->CI->output->get_output().



cache_override:

Enables you to call your own method instead of the _display_cache() method in the Output Library. This permits you to use your own cache display mechanism.

post_system:
Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.

Creating a hook :
$my_hook=array(
'class' => 'YourClassname',
'function' => 'your_function_name',
'filename' => 'your_filename.php',
'params' => array('p1', 'p2')
'filepath' => 'hooks', );
$hook['pre_controller'] = $my_hook;

3- Can we use multiple call to same hook?
Yes , we can use multiple call to same hook. Then We have to use multidimentional array:
$hook['pre_controller'][]= $hook_one;
$hook['pre_controller'][]= $hook_two;

4- What are the benifites of using hook in an application?
-We can modify core functionalitis without touching the core files.
-We can generate derired output without changing the view files.
-we can make a hook for recurring calls , like including footer and header in each function, without calling them in each controller function.
-we can create a script to minify the code before excecution take place.
-We can easily implement security checks, privacy, session, cache using hooks and can seperate these implementation from the main functionalitis.

5- WHat is HMVC?
HMVC is a Modular version of MVC. In this system we can implement modules for particular purpose. We may have put out controller , views and model in different modules. All these modules will be available in modules folder in application. HMVC stands for Hierarchical Model View Controller.



6- What is a module?

A module is a part of application and a full featured block which is implemented on HMVC pattern. A module contains its own Model, View and Controller. Although these resources can be shared with other modules.



7- What is difference between Library and Helper?


A CodeIgniter helper is a set of related global functions, you can call them any where in application. Once you load the helper file you can directly call the function. Basically the helper is procedural.

But a Library is a class, which you need to make an instance of the class. Once the library is loaded, we need to use $this operator to call the Library function. This is Object Oriented.




8- What is Routes in Code Igniter Framework?

Routing is the communication between URI and Controller. Routing decides the controller calls and parameters in code igniter. We can overwrite the routing rules in routes.php file.


9- How to use or enable libraries CodeIgniter?
We can initialize the library in controllers as given below:
$this->load->library('my_library_class');

10- Why CodeIgniter is a loosely coupled mvc framework?
CodeIgniter is called a loosely coupled mvc because, it provides unlimited flexibility to developers. It allows us to write and execute our custom codes, library, helpers. We can use call model and controllers functions in views and also can write custom code on views. It works like a core php when some one is going to manipulate it and on the other side it provide a modular structure to our application, XSS and CSRF functionalitis. It provides us lots of inbuilt library and also compatible with many more custome libraries. It never restricts us to write and execute any code.

Drupal Interview Questions and Answers

By Dhananjay → March 26, 2018

What is Drupal?
Drupal is an open source Content Management System and used for Complex websites. It has great flexibility of functionality and modularity. We can design our website using the core of Drupal and we can manage content on pages easily. Nowadays Drupal is used for e-commerce stores, blogging, business sites, college and universities websites.

What are the main features of Drupal?
Main features of Drupal are listed as:
-Open Source
-Flexible and Robust CMS in comparison to Others.
-Provide Security layer.
-Easy to manage Content.
-Fields and Blocks that are the most flexible assets of Drupal.

How Drupal is different from other CMSs available as opensource?
Drupal has a complex structure, and a heavy core so it is not suitable for small websites. It is secure than any other CMS.It has a great functionality to manage content and visibility. It provides a robust user management module in core.

What is the .info file in a Drupal theme?
This is the configuration setting of the Drupal theme. A .info file is a static content and settings are written here as key=value format. Each line has a different key and value for that. Metadata, style sheets, JavaScripts, block regions and more can be defined here. It is used for theme and not for the module.

What is a theme?
The theme is a collection of files to construct the layout. A Drupal theme contains following important elements:
- Configuration file (.info)
- Templates file (.tpl.php)
- Stylesheets
- sub-themes

What is Module in Drupal?
A module in Drupal is a collection of PHP files to provide some additional functionality to Drupal site. A module can access all the core functions and variables of the Drupal.

What is Block?
Blocks are the layout elements. A block defines that what particular content should be displayed at what place in the layout. It is a box in the content area.

How can we add modules to the core?
We can upload compressed files of the module or we can directly import from the remote URL.

What are the regions?
Regions are the layers defined by theme to represent the content area. For example footer, sidebar, navigation etc.

What is a node?
All the contents are treated as a node in Drupal. A node is a chunk of content. We create content, custom content using node module.

What is taxonomy?
Taxonomy is used to organize Metadata, tags, categories in Drupal. It a feature of Drupal core. It is used to categorize the content of the website. We can use tags to connect the content.

What is sub-theme?
A sub-theme is child theme. It inherits the resources of the Parent theme. It can be chained. A sub-theme can be a child of another sub-theme. All the styles sheets and javascript inherited by sub-theme.

What is service.yml?
service.yml placed in the root directory in and all the services are defined here.

What are properties of services?
Services may have following properties:
-abstract
-alias
-tag
-arguments
-calls
-class
-factory
-file
-public
-scope

What is settings.php?
This is the global settings of the site.Tthe database, URL structure, salt, encryption etc all the variables are defined here.

What is clean URL?
SEO friendly URLs in Drupal is clean URL.We can enable or disable it.

How can we manage clean URL in Drupal?
We can enable or disable clean URLs by following steps:
-navigate to Administer > Configuration > Search and metadata > Clean URLs
-Wait for the automated Clean URLs test to run.
-Check or uncheck the Enable clean URLs checkbox
-Click "Save configuration"

What is URL alias?
We can add our custom URL in place of "node". It makes URL clean and SEO friendly.

What does cron do in Drupal?
Cron deletes temporary files and trigger the search module to index the content on the site.It pings modules to get updates.

What is Report in Drupal?
Reports modules collect the site health report and logs.It does the following task:
-Recent log entries
-Top 'access denied' errors
-Top 'page not found' error
-Available updates
-Status Report
-Site statistics

What is the status report?
Here you can find a short overview of your site's parameters as well as any problems detected with your installation.

What is Recent Log entries?
The Database Logging module logs system events in the Drupal database. Monitor your site or debug site problems on this page.

What are the content types in Drupal?
Contents are categorized into 2 basic categories:
1- Basic pages
2- Articles

What is Basic page content?
Basic Page is the landing pages for a site, that rarely change. If we are creating About us, Contact us, Services, Team pages then we have to choose Basic Page type content.

What is Article type content?
Article type is a regular blog post on the site. We can select Article if we are writing an article or blog posts related to latest updates, hobbies etc.


15 Advance Code Igniter Interview Questions and Answer

By Dhananjay → January 23, 2018

How routing is beneficial in Code Igniter?
Routing provides a way to alter your URL and redefine it according to you. It helps in security and SEO. We can create URL having keywords and phrases influential for SEO ranking.

What is a helper?
Helpers are the file having functions for specific purposes. We can directly call them in our script.There is numerous type of helper:
  • Array Helper: It has functions that we use to manipulate arrays.
  • File Helper: Use of this helper is to play with files as upload an image.
  • HTML Helper : Html helper is used to compose HTML dom using php code.
  • URL Helper: We use it to create and construct or redirect URLs.

What does autoload.php do?
It loads when the application start loading contains and default parts of application call. It has information to load the segments that we need to load automatically. For example, we may need to load some models automatically.

How can we connect code igniter to our database?
There is a database.php file in the config directory. We can put here our database information like database name, hostname, username and password and It will be connected.

Can we call multiple model function in a single controller function?
Yes, of course. We can call any number of model and their functions in a single controller class?

Can we write database queries in a controller?
Yes, we can write database queries directly in controllers but this is not a good practice. We should write database queries always in the model.

How can we pass data to view?
We create an array having a particular key and pass this array to load view call. We will have this data on the view page as having the name of the key given to data array.

<?php
$data['employee']=array("name"=>"Dhananjay");
$this->load->view("employee_info",$data);
?>
Now on the employee_info.php page, we will have a $employee variable and that will store the data passed in the array $data in the controller.

How can we pass a parameter to controller function?
A parameter can be passed to URL segment after backslash next to function route. Suppose "admin" is a controller , "all_user" is a function and "active" is a parameter. Now we have to pass this to function that it can list the active user so we can call as given below:

<?php echo site_url("admin/all_user/active")?>

What is a library in Code Igniter?
Code Igniter library is a utility to extend the functionality and to use some predefined functions and classes. We have different libraries for different purposes as upload, database etc.

How can we execute a raw query in Code Igniter?
Using query builder library of code igniter we can execute raw query. For example,

db->query($sql);
$result=$query->result_array();
?>

What is URL helper?
We use URL helper to do manipulation with URL. We can easily create custom URL, we can extract parameters from URL, we can easily create custom anchors, form action, and page redirection.

How the database library provide strength to Code Igniter framework?
Database library has query builder functions. It works with single data and also in batch data. It accepts the array and single values as parameters. Functions are very similar to MySQL query phrases and keywords. We can use almost the query using query builder. It fetches the data in all possible formats. We can select, update, join, delete the records in very simple and robust way.

How we will submit data using a form on code igniter view?
We can give the controller function route as the form action. When we will submit this for, the controller function will be called and data will be collected using $_GET or $_POST arrays, as the method defined in the form.

How we create a session variable and how will we get that value stored in a session variable?
Code igniter has session library.It uses four types of the driver to store session data:
1-files
2-database
3-redis
4-Memcached
The file is the default storage.
After loading session library we can use session class and its method to set or get the session value.

<?php 
$this->load->library('session');
//set session data
$this->session->set_userdata('user_session_name', 'session_value');

//check session
$this->session->has_userdata('user_session_name', 'session_value');

//get session data
$this->session->get_userdata('user_session_name', 'session_value');

//destroy session data
$this->session->unset_userdata('user_session_name');
?>

How can we upload any file in Code Igniter application?
Code igniter has upload library. We will use this library and set preferences in $config variable.
After initializing library we use call do_upload() function and it will complete the task.

PHP-MySQL Interview Questions and Answers : Most Common Questions

By Dhananjay → January 19, 2018


There are some basic PHP Interview questions, asked in every interview often. They must be known to every interview aspirants. Chances of asking these questions by Interviewer is very high because they just test your basic concepts of PHP.They highlight your understanding and command of the language. They are helpful to nail the first impression on interviewer when you are in the interview. An Interviewer expects that you should know the answers to these questions. After these questions, you will be asked to answer some hard-core questions and concepts. What we have given here is experienced. these questions give you the pattern of often asked question on Interview along with their answers. We try to give genuine answers, by verifying them from www.php.net, www.w3schools.com, and other popular tutorials site. After knowing the pattern It will be easy for you to explore more questions from various sources.


What is PHP ?
PHP is a server-side scripting language. It is lightweight as well as enriched with OOPs features. PHP is freely available and has lots of frameworks, CMS to built robust and secure applications.

Explain these functions :
echo( ),print( ),print_r( ),die( ),exit( ),var_dump( )
var_dump($var):- Displays information about a variable.
echo() or echo: This is not actually a function.This doesn't return a value after it takes parameter.
print() pritn : This is also not a function ,accepts always single parameter and returns 1.
print_r():-This prints the content and indexes of arrays and objects.
exit:-It terminates the current script with a message.
die(): This is identical to exit;

What are the differences amongst include(), require(),require_once(), require(),include()?
include(): Includes an external script into current script. On failure it emits Warning and allows script to continue, it does not terminate the execution of the script.
include_once(): On failure emits an compile E_COMPILE_ERROR  error. It terminates the script execution.

What is the difference between in_array() and is_array()?
Both of these function returns a boolean type.
in_array() :
If a value finds within an array it returns TRUE otherwise returns false.
is_array() :
It checks whether the type of variable is an array or not. It returns true if an array is passed into it. It can be applied to any type of array.

What is the difference between count() and sizeof()?
Literally we can say there is no difference between these two terms. Both of these have Identical behaviors.
count():- It counts all elements of an array or object.
sizeof():-Identical to count(), can say Alias.

What is the difference between json_encode() and json_decode()?
json_encode() converts a PHP array or an object into json string, and json_decode() convers an JSON string into PHP array or into PHP object.

Where do we store Session and Cookie?
The session is stored on server whereas cookies are stored on the client machine in browsers.

How we use foreach loop in PHP?
Foreach loop is used to iterate an array or an object in PHP . For example

<?php 
foreach ($array as $key =>; $value){
echo "$value is at $key place";
}
?>

What are the differences amongst trim(),ltrim(),rtrim()?
  • trim():-It removes white spaces from both the sides of a string.
  • ltrim():-It removes white space from left side of a string.
  • rtrim():-It removes white space from right side of a string.
What are the constants , how we define them in PHP?
A constant is a name assigned to a value. It is like Identifiers but cannot change during script execution. We can define them usually in UPPER_CASE underscored string without $. For example: define("CURRENT_YEAR", "2017");

What is $_GLOBAL?
$_GLOBAL Is a superglobal array and holds all the variables that are global and can be accessible from anywhere in the script. $_POST,$_GET,$_REQUEST,$_FILE,$_SESSION,$_COOKIE all are superglobal arrays available in PHP. We can call them anywhere in the script.

What is the difference between MySQL and mysqli?
MySQLi is the extension of MySQL and It is an improved version of MySQL. MySQLi supports OOPS features and compatible to PDO.

What unlink() function do in PHP?
It is used to delete a file or directory from its location.

What are the basic differences amongst Warning, Fatal Error, and Notice?
Fatal error results in the termination of script, No further execution of the script is possible when it happens. Whereas Notice does not terminate the script, rather it notifies about some tolerable mistake and script after that line is able to execute. Warnings are the deprecated and bearable things in scripts. The doesn't affect the result usually.

What is the difference between array_diff() and array_filter()?
array_diff() returns the array of values of difference of two arrays and array_filter() returns the arrays of values and filter null values or specific values. The function array_filter() also used a callback function but it is optional.

What is the difference between array_serach() and in_array()?
The method array_search() returns the key if the value is found in the array and the function in_array() return TRUE if it will find the values in the array. In case of a failure, both functions return FALSE.

What strlen() do?
strlen() is a PHP library function and it returns the length of string passed to it.

How substr() works?
substr() is a PHP library function and it returns the part of string passed with parameters to it. It accepts starting point, length of returning string and input string as parameters.

How str_replace() works?
It is used to replace a sub-string with another substring in an input string.

Top 10 Interview Questions and Answers for PHP freshers

By Dhananjay →
What is difference between $_GET and $_POST?
$_GET stores data sent by HTML form 'get' method or the value of variable encoded with URL whereas the $_POST collects the data submitted by "post" method of HTML form. $_GET has a character limit whereas no such limit defined by PHP for the POST.

How many types of array are there in PHP?
Basically, there are three types of arrays in PHP
1- Indexed arrays
2- Associative arrays
3- Multidimensional Arrays

How to convert a string into array and vice-versa?
We can cover an array into a string and a string into an array using explode() and implode() methods.These methods use some delimiter to concat values of arrays and also at the time of splitting a string into an array.


How you can find IP address of Local machine accessing PHP sites?
PHP has a number of superglobals.$_SERVER has some autodetected values. We can use this variable to get the IP address as given below:

1
$_SERVER['REMOTE_ADDR'] ; ?>


In how many ways we can fetch data from MySQL database?
There are four standard ways to fetch data from MySQL database in PHP. They are listed below:
1-mysql_fetch_array()
2-mysql_fetch_assoc()
3-mysql_fetch_row()
4-mysql_fetch_object()

Is PHP an Open Source?
Yes, PHP is absolutely free, and it is an Open Source.It can be used under GPL.

Does PHP supports OOPs Features?
Yes, PHP is a full-featured server-side scripting language and enriched with Object Oriented Programming system approach. We can define a class, constructor. We can create Objects and can implement oops features like Abstraction, Polymorphism, Inheritance, and Encapsulation.

What is the difference between array_merge and array_combine?
We can differentiate between the two terms while understanding their definitions.
array_merge(): Merge Elements of arrays in a single array while preserving their indexes. But array_combine() returns a new array where values in one array are keys in new arrays and values of another array values in new arrays.

What is the Latest stable version of PHP and MySQL?
You should check these things before your Interview because the version the things are updating frequently.
For PHP: www.php.net
For MySQL: www.mysql.com

Code igniter Interview Questions and Answers

By Dhananjay →


What is MVC?
MVC is a three-tier architecture of application development approach.Almost the popular languages use this pattern. MVC provides Modular structure to an application. Three interconnected parts are Model, View, and Controller.
M: Model, that means data handling and information interchange. Implement CRUD.
V: view i.e. front end and representational parts, where user interacts with machine
C: Controller, The business login, handle user request an passes to model and in return provide results to the user.

What is difference b/w MVC and HMVC?
HMVC is a hierarchical MVC, The whole application is modularized in interconnected modules and each module has its own MODEL, VIEW, CONTROLLER. In HMVC a module is a complete package of User Interface, business logic, and data handling. So MVC is discrete whereas HMVC contains MVC at each level.

How we can load a model in CI controller?
We can call load a model in the constructor as given in the following example:

1
2
3
4
//load model $this->load->('users_model','users');
//call model
$this->users->add_new_user($data);
?>

We can also assign an alias to ci_model. We can use 'users' to call a model rather than calling 'users_model'.

What is autoload.php in the config?
This is a file where preloaders are defined. Suppose we want to include database library, any model, URL library, sessions etc, then we can assign all these things here.

What helpers do in CI?
Helpers are the simple PHP functions returning some values and we can call them anywhere in our project once we initialized them.

What are the libraries in CI, explain some popular libraries?
The library is the packages which are designed to implement a particular set of functionalities. For example Database. Once we Initialized it, we do any operation on the database.

What are Hooks?
Hooks provide flexibility to CI core. We can modify the core functionality of CI without disturbing core files and use hooks.Learn more about Hooks in CodeIgniter

How we define URL and redirect in CI?
We use URL helper and then we can create redirect links :

1

these functions provide the way to create URL.

How to write a SELECT query in CI model?
We can write a select query in code igniter using the standard conventions of CI as given below:

1
2
3
4
//table name 'users' $this->db->select('users');
$query=$this->db->get();
$result=$query->result();
?>

How to call a CI model Controller?
The following example illustrates, how to call a model in code igniter controller:

1
2
3
4
//load model $this->load->('users_model','users');
//call model
$this->users->add_new_user($data);
?>

What are the views?
A view is the display part of the application. It renders the results on screen and provides UI.We can assemble views files in directories as well.

How we define controller in CI?
A controller is the backbone of MVC. It creates a connection between model and view.We can define a controller as illustrated:

1
'BASEPATH') OR exit('No direct script access allowed');

How controllers and models are different?
Controllers deals with business logic. When user Instruct the machine to do something, controller listens to that response while interaction another side with a model for data. Whereas a model is data handling layer. It saves data to the database and it requests data from the database that further goes to the controller to display on view.

What is the convention to call controller function with a parameter in CI?
We can call a controller function in uri using the a pattern given below. First part of URI is base URL. Base URL followed by controller route and followed by function name , parameters.
base_url/controller_name/controller_function/param1/param2
[Controller Class]/[controller methos]/[parameters]

How to write JOIN Query in Code Igniter?
Code Igniter has a very rich Database library. It provides a flexible way to call and create logics. Either we can use raw queries or we can use join() function.

1
2
3
4
5
6
$this->db->select('t1.name,t2.email');
    $this->db->from('table1 as t1');
    $this->db->join('table2 as t2', 't1.id = t2.user_id', 'left');
    $query = $this->db->get();
    return $query->result();
?>

How to apply where clause in Code Igniter?
Using Code Igniter Database library function 'where()' we can apply where clause.

1
2
3
4
5
6
7
8
$where=array( 'email'=>me@example.com,
'status'=>'active'
);
$this->db->select('name,email,mobile');
$this->db->get('users');
$query=$this->db->where($where);
$result=$query->result();
?>

What is routing?
Routing is a way to define URI and how to call controller methods with a particular URI.
Routing provides flexibility to change the way we call controller functions. We can rename controller and functions. This enhances the security features as well as we can create SEO friendly URLs.

What is the way to fetch query results in CI?
Ther are many ways to fetch result in Code Igniter. Some of them are as follows:
result();
result_array();
row();
row_array();
unbuffered_row();

How we call controller method using AJAX?
Simply we can call the URL using proper method and parameters, and then handle those request on a controller and if required we can render a view.

How to define a session variable in CI?
First of all, we need to load session library and then we can call some library functions to accomplish this task:

1
2
3
4
//load library $this->load->library('session');
//define a session variable named 'user_id'
$this->session->set_userdata('user_id', $user_id);
?>