Category Archives: Web Development

Articles and Interview Questions,Tips related to Web Development – Interview Sortout

Python Interview Questions

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. 

Nowadays the popularity of python is increasing day by day. Python is easy to learn and has vast libraries. In the field of Machine Learning, Deep Learning and Artificial Intelligence Python are the top priority in the implementation tool.  You can find on google the trends of top programming languages.

Since the demand and popularity are on top, so the career opportunity in Python programming and related fields is high. Keeping this in mind we have created a set of some useful Python Interview Questions and Answers, so that one may find a proper guide for an Interview. 

Python Interview Questions are very useful when you are going for an Interview for the designation of Python Developer or Machine Learning or any Related fields to Python. These python interview questions and answers are equally useful for freshers and experienced.

While representing this set of questions along with answers we hope that they will be useful for visitors.

What is Python?

Python is an Interpreted programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, built-in data structure and it is open-source.

What are the key features of Python?

  • Python is an interpreted language. That means Python does not need to be compiled before it is run. 
  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. 
  • Python is well suited to object-orientated programming in that it allows the definition of classes along with composition and inheritance. 
  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first-class objects
  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. 

What type of language is python? Programming or scripting?

Python is capable of scripting, but in a general sense, it is considered as a general-purpose programming language.

What is PEP 8?

PEP 8 is a coding convention, a set of recommendations about how to write your Python code more readable.

What are Python packages?

Python packages are namespaces containing multiple modules.

What is the difference between abs () and fabs ()?

abs() is a built-in function that works with integer, float and complex numbers also.

fabs() is defined in the math module which doesn’t work with complex numbers.

How Python is interpreted?

Python is an interpreted language because Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

How memory is managed in Python?

Python has an awesome feature of memory management. The following points will explain memory management in python:

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and the interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

 

What are the tools that help to find bugs or perform the static analysis?

PyChecker is a static analysis tool that detects bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

 

What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

 

What is the difference between list and tuple?

The difference between list and tuple is that the list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

 

How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.

 

What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

 

What is the built-in type does python provides?

There are mutable and Immutable types of Pythons built-in types Mutable built-in types

  • List
  • Sets
  • Dictionaries

Immutable built-in types

  • Strings
  • Tuples
  • Numbers

 

What is namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as a namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.

 

What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

A deep copy is used to store the values that are already copied. The deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

 

What is lambda in Python?

It is a single expression anonymous function often used as an inline function.

 

Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make a new function object and then return them at runtime.

 

Does python support multiple inheritances?

Multiple inheritances mean that a class can be derived from more than one parent class. Python does support multiple inheritances, unlike Java.

 

What is a pass in Python?

Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.

 

What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

 

What is encapsulation in Python?

Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.

 

How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

 

How to use access specifiers?

Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.  

 

In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like a list.

 

What is the unit test in Python?

A unit testing framework in Python is known as a unit test. It supports the sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.

 

Explain what Flask is and its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify it. The user can modify the session if only it has the secret key Flask.secret_key.

 

In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.

 

What are the generators in Python?

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

 

What is PYTHONPATH?

It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

 

What is type conversion in Python?

Type conversion refers to the conversion of one data type into another.

int() : converts any data type into integer type

float() : converts any data type into float type

ord() : converts characters into integer

hex() : converts integers to hexadecimal

oct() : converts integer to octal

tuple() : This function is used to convert to a tuple.

set() : This function returns the type after converting to set.

list() : This function is used to convert any data type to a list type.

dict() : This function is used to convert a tuple of order (key,value) into a dictionary.

str() : Used to convert integer into a string.

 

What is docstring in Python?

A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

 

How can you copy an object in Python?

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

 

What is a negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

 

How you can convert a number to a string?

In order to convert a number into a string, use the inbuilt function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().

 

What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

 

Mention the differences between Django, Pyramid, and Flask.

  • Flask is a “microframework” primarily build for a small application with simpler requirements. In a flask, you have to use external libraries. Flask is ready to use.
  • Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
  • Django can also be used for larger applications just like Pyramid. It includes an ORM.

 

What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

 

Why indentation required in python?

Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

 

Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

List out the inheritance styles in Django.

In Django, there are three possible inheritance styles:

  1. Abstract Base Classes: This style is used when you only want the parent’s class to hold information that you don’t want to type out for each child model.
  2. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
  3. Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.

 

Why are local variable names beginning with an underscore discouraged?

  • they are used to indicate a private variables of a class
  • they confuse the interpreter
  • they are used to indicate global variables
  • they slow down execution

 

What is the purpose of the PYTHONCASEOK environment variable?

PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

 

Explain how can you make a Python Script executable on Unix?

To make a Python Script executable on Unix, you need to do two things,

  • Script file’s mode must be executable and
  • the first line must begin with # ( #!/usr/local/bin/python)

How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

 

What are the supported data types in Python?

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

 

Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

 

Explain how you can generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating-point number in the range [0,1)

 

What is self in Python?

 

Self is an instance of an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional.  It helps to differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

 

What are tuples in Python?

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

 

How will you check if all characters in a string are alphanumeric?

We will use the method isalnum().

 

Does Python allow you to program in a structured style?

Yes. It does allow to code is structured as well as Object-oriented style. It offers excellent flexibility to design and implement your application code depending on the requirements of your application.

 

Explain how can you access a module written in Python from C?

You can access a module written in Python from C by following method,

Module = =PyImport_ImportModule(“<modulename>”);

 

Mention the use of // operator in Python?

It is a Floor Divisionoperator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

 

Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners

What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of the Python program is a package of modules. A package can have modules or subfolders.

 

What is difference between pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

  • Having the built-in data types saves programming time and effort from declaring variables

 

What is a dictionary in Python?

Ans: The built-in data types in Python are called the dictionary. It defines one-to-one relationships between keys and values. Dictionaries contain a pair of keys and their corresponding values. Dictionaries are indexed by keys.

 

Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all the words present in the string.

 

What tools can be used to unit test your Python code?

The best and easiest way is to use ‘unittest’ python standard library to test units/classes. The features supported are very similar to the other unit testing tools such as JUnit, TestNG.

 

What is the starting point of Python code execution?

As Python is an interpreter, it starts reading the code from the source file and starts executing them.

 

Explain what is Flask & its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jinja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.

 

Mention what is the difference between Django, Pyramid, and Flask?

Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.

The pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. The pyramid is heavily configurable.

Like Pyramid, Django can also used for larger applications. It includes an ORM.

 

How to comment on multiple lines in python?

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment on multiple lines. All you need to do is hold the ctrl key and left-click in every place wherever you want to include a # character and type a # just once. This will comment on all the lines where you introduced your cursor.

 

Which module(s) of Python can be used to measure the performance of your application code?

Time module can be used to calculate the time at different stages of your application and use the Logging module to log data to a file system in any preferred format.

 

Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads

 

Does the same Python code work on multiple platforms without any changes?

As long as you have the Python environment on your target platform (Linux, Windows, Mac), you can run the same code.

How do you make use of Arrays in Python?

Python does not support Arrays. However, you can use List collection type which can store an unlimited number of elements.

Explain what is the common way for the Flask script to work?

The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

 

What are the different environment variables identified by Python?

PYTHONPATH: This environment variable helps the interpreter as to where to locate the module files imported in the program.

PYTHONSTARTUP: This environment variable contains the path of the Initialization file containing the source code.

PYTHONCASEOK: This variable is used to find the first case-insensitive match in the import statement

 

Explain how you can access sessions in Flask?

A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.

 

What are a help () and dir() in python?

help() is a built-in function that can be used to return the Python documentation of a particular object, methods, attributes, etc.

dir() displays a list of attributes for the objects which are passed as an argument. If dir() is without the argument then it returns a list of names in current local space.

 

What is the difference between locals() and globals ()?

locals() is accessed within the function and it returns all names that can be accessed locally from that function.

 

Spread the love

What is New in PHP 7

PHP 7 is introduced as the next version of PHP.

The earlier one is PHP 5.6. The latest version is scalable and more flexible, faster and easy to implement complex logic.

Many new features are introduced with PHP 7.

These features are equally useful for the interview aspirants. Few of them are explained :

PHP 7 Features

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Unicode codepoint escape syntax
  • Closure::call()
  • Group use declarations

Scalar type declarations

There may be two scalar types of declarations :

  • coercive(default)
  • strict

We can enforce the types for parameters either coercively or strictly are :

  • strings (string)
  • integers (int)
  • floating-point numbers (float)
  • booleans (bool)

For Example in Coercive mode:

<?php
	function addTheNumbers(int ...$ints)
	{
	    return array_sum($ints);
	}
	var_dump(addTheNumbers(3, '7', 7.8));
?>

Declaration of Return Type

PHP 7 started support for return type while declaring a function.
The return type declarations specify the type of value that will be returned after execution.

For example :

<?php
function sumOfArrays(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(sumOfArrays([10,20,30], [14,15,16], [17,18,19]));
?>

In the above function, the accepted argument are arrays and the return type of the function is also an array.

Null coalescing operator

This is a comparison and validation operator added to PHP 7 and It is used as a ternary in conjunction with isset() function.
If the expression exists and not NULL then it returns the first operator else it returns the second one.

For example :

<?php
	$booktitle = $_GET['title'] ?? 'no_books';
?>

If the title is set in $_GET and the value of the $_GET[‘title’] is NOT NULL then the value of $booktitle will be the $_GET[‘title’]. In a condition of failure the title will be ‘no_books’.

Spaceship operator

This is a pure comparison operator and compares the values of two variables. It returns -1, 0 and 1. It compares less than, equal to and greater than.

Have a look at examples :

<?php 
// Integers
echo 7 <=> 7; // 0
echo 7 <=> 8; // -1
echo 8 <=> 7; // 1

// Floats
echo 7.5 <=> 7.5; // 0
echo 7.5 <=> 8.5; // -1
echo 8.5 <=> 7.5; // 1

// Strings
echo "b" <=> "b"; // 0
echo "b" <=> "c"; // -1
echo "c" <=> "b"; // 1
?>

Constant arrays using define()

In PHP 7 we can define an array as a constant, like strings and numbers. It can be done using the define() function.

<?php
define('SUPER_HEROS', [
    'Iron Man',
    'Thor',
    'Captain America',
    'Spidar Man'
]);

echo SUPER_HEROS[1]; // outputs "Thor"
?>

Anonymous classes

PHP 7 has introduced support for Anonymous classes. Anonymous classes can be used in place of the full class definition for throwaway objects.

<?php
interface Logger {
    public function log(string $msg);
}

class Application {
    private $logger;

    public function getLogger(): Logger {
         return $this->logger;
    }

    public function setLogger(Logger $logger) {
         $this->logger = $logger;
    }
}

$app = new Application;
$app->setLogger(new class implements Logger {
    public function log(string $msg) {
        echo $msg;
    }
});

var_dump($app->getLogger());
?>

Unicode codepoint escape syntax

A valid Unicode codepoint character can be converted to UTF-8 corresponding character. All the leading 0’s will be neglected.

<?php 
	echo "\u{aa}";
	echo "\u{0000aa}";
	echo "\u{9999}";
?>

The above example will output:

ª
ª (same as before but with optional leading 0’s)

Closure::call()

Closure::call() is a way of temporarily binding an object scope to a closure.


<?php class MyClass { private $val = 1; } $getVal = function() {return $this->val;}; 
echo $getVal->call(new MyClass);
?>

Group use declarations

Classes, functions, and constants being imported from the same namespace can now be grouped together in a single-use statement.

<?php
	use some\namespace\{ClassA, ClassB, ClassC as C};
	use function some\namespace\{fn_a, fn_b, fn_c};
	use const some\namespace\{ConstA, ConstB, ConstC};
?>

Here we don’t need to import one by one, we can import all the classes in a single call. Similarly the functions and constants also.

Now we are able to understand the new updates in PHP 7. Hope this will help. Happy Learning 🙂

Spread the love

In How many ways we can use Model in CakePHP

CakePHP is an MVC based framework and facilitates unlimited flexibility. A model in cake PHP is used for the data source and all the logics that require to gather the data.

Later we use a Model functions to get these formatted data in Controllers and send them to view using the set function.

Here we are going to learn in how many ways we can use a Model or data source in CakePHP applications.

The naming convention followed in CakePHP help us to reduce our effort and to make the development process rapid.

Since Model is used as a logical unit and data source we can use it in any Controller where we need the data, irrespective the name of model and controllers.

A Controller with name “Users” can access the functions written in Model User without any manual initialization. But the question is how to use another Model and its functions in Users Controller?

When we are developing a complex application we usually need to access data from many tables or we can say from many Models in a single controller.

If there is no association then we need to initialize the other Models manually. Once we initialize these models we can use any functions in these models in the Controller. We can use any data source in any controller.

Even we can use the Model in our plugins Model, in the same way, we use in our standard models.

There are different ways to initialize a model in any Controller:

  • Initialize at the start of Controller and use it in any action of Controller.
  • Initialize in the particular action of Controller.
  • Initialize and Using in Another model.

Initialize at the start of Controller and use it in any action of Controller

There are many such situations when we need to use any model continuously in all the functions, then we need to initialize a model that can be used from anywhere.

Here we once initialize the model is available anywhere in a controller to use. We should not use this method when we are using the Model in only a few functions.

This may create overhead to the application when each time a data source is being loaded without reason.

Initialize in a particular action of Controller

When we have limited usage in a controller then it is not a good practice to initialize a model at the start.

We should initialize when we need only.

There may be some particular function that needs to access data from another model.

Initialize and Using in Another model

There are many such situations arrived when you need to use another model functions in your model, then you need to import that model in your model.

When we need additional data apart from association we need to fetch data from a model that is not the current model. CakePHP provides flexibility to use a number of existing model functions in your model.

This facilitates code reusability and improves the maintainability of application and at the same time reduce overhead and development time.

Hope this article will help you in using a model in Cake PHP in different ways.

Happy Learning 🙂

Spread the love

How to add additional fields to user profile in WordPress

WordPress is the most-popular CMS and provides unlimited flexibility to users to do anything they wish.

To maintain its flexibility and maintainability WordPress provides hooks. Using these hooks we can extend the functionality and customize the interfaces as per requirement.

WordPress provides metadata to add additional information with content.

Using these meta we can add number of custom fields with any content like post, page,media,user,category,terms etc.

Here we would know that how to add an additional field to user profile?
For example we have to add highest educational qualification of users.

So we need to to add a user meta for this field. Let the field name is highest_qualification.

We will hook the user meta to the hooks related to user profile. Available hooks for user profile are:

  1. show_user_profile
  2. edit_user_profile
  3. personal_options_update
  4. edit_user_profile_update

These hooks enable user to add and update the meta field. Lets have a look on code snippets:
STEP #1: Add form field when user is going to edit the profile details:

Create a function add_user_educational_qualification and hook it with show_user_profile and edit_user_profile.

<?php
    add_action( 'show_user_profile', 'add_user_educational_qualification' );
    add_action( 'edit_user_profile', 'add_user_educational_qualification' );
    function add_user_educational_qualification( $user ) { ?>
	    
    <table class="form-table">
     <tr>
      <th>
       <label for="address"><?php _e("Highest Educational Qualification");?></label>
     </th>
     <td>
      <input type="text" name="highest_qualification" id="highest_qualification" value="<?php echo esc_attr( get_the_author_meta( 'highest_qualification', $user->ID ) ); ?>" class="regular-text" />
     <span class="description"><?php _e("Please enter your heighest Educational Qualification."); ?></span>
    </td>
 </tr>
</table>
<?php }  ?>

STEP #2 : Now we need to save this information to user_meta table , so we need the hook that are used to save or update the user profile and details.

Create a function save_user_educational_qualification and hook it with personal_options_update and edit_user_profile_update.


	add_action( 'personal_options_update', 'save_user_educational_qualification' );
	add_action( 'edit_user_profile_update', 'save_user_educational_qualification' );

	function save_user_educational_qualification( $user_id ) {
	    if ( !current_user_can( 'edit_user', $user_id ) ) { 
	        return false; 
	    }
	    update_user_meta( $user_id, 'highest_qualification', $_POST['highest_qualification'] );
	}

STEP #3: Now we need to display this information any where in the website:

We are ready with our additional field highest_qualification. We have added it and saved it to database.

WordPress provide a function highest_qualification and using this function we can get the value of meta fields.

 


<?php 
   $meta_key = 'highest_qualification'; 
   $highest_qualification = get_user_meta( $user_id, $meta_key,true); 
?>
Spread the love

What is the Storage Engine in MySQL

Following Question Based on MySQL Storage Engine covered in this Section:

  1. What is storage engine?
  2. How many types of storage engines are there in MySQL?
  3. What are the features of Different type of storage engines?
  4. Why Memory is faster than MyISAM and InnoDB?
  5. Which one is the Transaction Compatible Engine?
  6. Which are the storage engine in MySQL , do not use Indexing?
  7. What are the main difference between in MyISAM and InnoDB?
  8. Which version of MySQL support Transaction?

MySQL Storage Engine

Storage Engine in MySQL is the bottom most layer and stores data in various formats. Based on their techniques and compatibility for different types of application we choose which one would be suitable. MySQL has number of storage engines. Few of them are transactional and few are non-transactional. Here is the list of popular storage engines in MySQL:

  1. MyISAM
  2. InnoDB
  3. Memory(HEAP)
  4. Archive
  5. CSV
  6. MERGE

MyISAM

This is a non-transactional storage engine and a table can hold up to 256 TB data. Before MySQL 5.5 MyISAM was the default storage engine, but after Introduction of transaction support InnoDB is the default storage Engine in MySQL. Data in MyISAM is compressed and optimized for quick access. Earlier it was known as ISAM. It can repair the corrupted tables itself on startup.

InnoDB

InnoDB is the most widely used storage engine now a days and used as a default storage engine in MySQL. It is transaction safe and compatible to ACID properties of database transactions. It supports all the DML, DDL and DCL operations. It can hold up-to 64 TB data in a table. It also uses compression techniques to store data.

MEMORY

Memory Engines store data in Memory. It uses the hash index techniques to store data and hence the access of data is comparatively faster than MyISAM and InnoDB. In Memory data is stored in the form of HEAP tables.

Archive

The engine is used for archiving the records. It can be used to archive the huge amount of data and records. It stores data in compressed format and when an access request is come it serves the data after decompressing the archives. We can not have Indexing in Archive engines so we have to scan all the data to get the particular records.

CSV

CSV is a well-known spreadsheet format. It is also used for Non-SQL based systems to store and retrieve data. Data is stored CSV format or comma separated formats. This is also a non-indexing technique. We can not have a NULL value in CSV. It also required to read full table to get a record. Hence it is slower than InnoDB and MyISAM.

MERGE

MERGE is storage engine that uses MyISAM tables as component and merged them to store as a single table. MERGE tables use Indexes of component tables, they do not have their own indexes. When we run DROP command then It does not drop tables in real, but the merger splits.

Spread the love

PHP Advanced Interview Questions and Answers For Experienced

We brought here some advanced PHP interview questions that need special attention while preparing for an Interview.

We have collected these questions and answers from various sources and candidates have been appeared in multiple PHP Developer Interviews.

These questions are useful for Freshers searching jobs for PHP developers and also for the people looking for a change having 2+ years experience.

Find the latest PHP MySQL interview questions and answers for experienced in 2020.

These are not pure practical based questions but they have a huge impact on your selection for the right job.

How we can set default time-zone in PHP?
Using library function date_default_timezone_set() we can set default time-zone:

<?php date_default_timezone_set("America/New_York"); echo "Time in Default Zone is : " . date("h:i:sa"); ?>

What is difference between == and === ?
Both are the comparison operator. The first one (==) is ‘Equal to’ and the second one (===) is ‘identical to’. ‘Equal to’ is used to compare the values of variables. ‘Identical to’ is used to compare values as well as the type of variables.

For Example :

<?php $x = 1250; $y = '1250'; if($x==$y){ echo 'X and Y are Equal'; }else{ echo 'X and Y are Not equal'; } if($x===$y){ echo 'X and Y are Identical'; }else{ echo 'X and Y are Not Identical'; } ?>

What is difference between != and !== ?
Both are the comparison operator. The first one (!=) is ‘Not Equal’ and second one (!==) is ‘Not identical’. ‘Not equal’ is used to compare the values of variables. ‘Not Identical’ is used to compare values as well as the type of variables.

For Example :

<?php $x = 1250; $y = '1250'; if($x!=$y){ echo 'X and Y are Not equal'; }else{ echo 'X and Y are Equal'; } if($x!==$y){ echo 'X and Y are Not Identical'; }else{ echo 'X and Y are Identical'; } ?>

How do I get PHP Errors to display?
Use the following code snippet to on error reporting in a PHP script:

<?php 
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);

But we can not display PHP parse error this way. We need to modify php.ini file and need to ‘on’ the display error:

display_errors = on

What is the difference between Notice Errors and Warning Errors in PHP?
Notice and Warning are the Non-fatal Errors and Not let the script halted.
Notice is an Advisory message regarding what you should prefer to do with this line of code.
For example, using an undefined variable is a Notice.

 

 

 

The warning is the message saying that you are going wrong and that may cause an error in the future so, you may correct that. For example, including a not existing script will throw a Warning.

 

 

What is the use of break and continue in the PHP loop?
Break: It terminates the loop and exit from the iteration.

Continue: It escapes the current iteration and starts a new iteration in the loop.

What are the common types of errors that occur in Php execution?

Php has Identified numbers of Error detection categories. Following are the common errors in PHP:

E_ERROR: A fatal error and halts the script from further execution.

E_WARNING: Run time warning that detects something is wrong that you need to correct to avoid future errors.

E_PARSE: Compilation error when the code is parsed. We need to on the error reporting in php.ini file to get this.

E_NOTICE: Run time notice to notify that you should go follow the suggested message.

E_CORE_ERROR: It is a fatal error that halts the script and occurs at the initial startup of PHP.

E_CORE_WARNING: Warnings that occurs at the initial startup of PHP.

E_COMPILE_ERROR: Fatal error on compilation occurs at the initial startup of PHP.

E_USER_ERROR : User-generated error message.

E_USER_WARNING: User-generated warning message.

E_USER_NOTICE: User-generated notice message.

E_STRICT: Run-time notices.

E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error

E_ALL: Catches all errors and warnings

Difference between mysql_connect and mysql_pconnect?
When mysql_pconnect() is used to create and maintain a persistent connection to the database that means a SQL link that does not close when the execution of your script ends whereas mysql_connect() creates a new connection each time when it called.

When a persistent connection is created and again a connection request is called the mysql_pconnect() return the earlier established connection rather than creating a new instance of connection.

What do you understand by &$name?
Using the reference of the variable rather than a copy of that.

If we pass the reference of a variable in a function as an argument and the value is changed then the value of the original variable outside the function is also changed.

This is passing by reference.

What is New in PHP 7?
PHP 7 has many new features. Here is the list of PHP 7 New features:

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Unicode codepoint escape syntax
  • Closure::call()
  • Group use declarations

When you are going for a PHP Developer job you should also focus on Jquery Interview Questions, PHP-MySQL Interview Questions, PHP Functions asked in Interviews.
I hope you enjoyed learning. You can ask any question based on the Above topic or you can submit questions here in the comment box.

Spread the love

CakePHP 4.0.0 alpha is released

The new and most awaited version of the rapid development framework is released by the core team of CakePHP.

The alpha released yet is not recommended for development purpose, until the stable version come. Removing the drawbacks and implementing new features , library support and improved performance the new version of cakephp will be rocking soon.

What are the new features in CakePHP 4.0.0

The Directory structure and the Bake console is rewritten to ease the development process and to increase development speed.

CakePHP was using Foundation framework for CSS and UI , but they are going to discontinue this associations and will go with the new one i.e. milligram.

Automatic Time zone handling by the ORM if any difference is found between Database timezone and server timezone.

All the deprecated features will be removed completely in new version.

CakePHP will not support PHP 5.6 and PHP 7.0, The minimum version that will be acceptable is PHP 7.1.0. Further It will be modified to PHP 7.2.0 as a minimum acceptable version of PHP.

An improved type-hinting will be added.

Error and warning reporting system is improved.

Validation messages will be embedded in Form helper and date-time input is introduced.

Authentication functionality has been split into standalone plugins Authentication and Authorization.

Spread the love

How to start with Codeigniter

What is Codeigniter?

Codeigniter is a PHP based Web development framework.Code igniter follows MVC and HMVC pattern for application development. This is one of the easiest and the simplest MVC frame work available in PHP. It doesn’t demand any configurational setting before execution. We just need to download the Codeigniter source code and to execute it on webserver.

How to and from where we will find the CodeIgniter?

We can download the latest release source code from official website of CodeIgniter [https://codeigniter.com/download]. It is a 2.7 MB zip file for CodeIgniter 3.1.10.

We can also clone it or fork it from Git Hub [https://github.com/bcit-ci/CodeIgniter].

When we will extract we will find 3 folders

  1. application
  2. system
  3. user_guide

application – is what we will use for creating modules,display and our logic will remain there in Models,Views and Controllers.

system – folder is core files of CodeIgniter, that we don’t need to work on.

user_guide – is the tutorial, documentation and examples of how to use Code igniter and this is the best documentation available for any MVC framework.

How to configure it?

No any configuration required. Just put the extracted folder inside your localhost directory and run it, You will find a welcome home screen.

default-home-page-of-codeigniter
Spread the love

Common Programming Interview questions and Answers

No, any technical interview can be completed without logical questions based on simple programming techniques. When you are going for a Programmer profile, you must know the simple logic applied to make complex programs. Here is the collection of such important logical questions asked in an interview.These collection includes reverse string,factorial,star printing pattern,swap,leap year,prime number,odd-even number,palindrome etc.

 

Write PHP script to reverse string without using any PHP function.


	function reverseString($string){
		$i=0;
		$output_string='';
		while($string[$i]){
			$output_string=$string[$i].$output_string;
			$i++;
		}
		return $output;
	}
	$my_string="this is a string to be reversed";
	$output=reverseString($my_string);

 

Write a program to find Factorial Of a number without using recursion.


function findFactorial($n){
	$factorial = 1;
	if($n&amp;lt;=1){
		return $factorial;
	}else if($n&amp;gt;1){
		$i=0;
		while($n-$i){
			$factorial = $factorial*($n-$i);
			$i++;
		}
	}

	return $factorial;

}
echo findFactorial(10);

 

Write a program to find Factorial of a number using recursion.


function findFactorialRec($number){
	if($number &amp;lt;= 1){    
        return 1;   
    }   
    else{   
        return $number * findFactorialRec($number - 1);   
    }   
}
echo findFactorialRec(10);

 

Write a program to print the following Pattern

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *


$n=5;
for ($i=1;$i&amp;lt;=$n;$i++){
	for ($j=0; $j &amp;lt; $i ; $j++) { 
		echo "# ";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a program to print the following Pattern.

                                 *
                             *  *
                          *  *  *
                      *  *  *  *
                   *  *  *  *  *


for ($i=1;$i&amp;lt;=$n;$i++){
	for ($j=$n-$i; $j &amp;gt; 0 ; $j--) { 
		echo "+";
	}
	for ($k=0; $k &amp;lt; $i ; $k++) { 
		echo "*";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a program to print the following Pattern.

                                  *
                               * * *
                            * * * * *
                         * * * * * * *
                      * * * * * * * * *


$n=5;
for ($i=0; $i &amp;lt;$n-1 ; $i++) { 
	for($j=$n-$i;$j&amp;gt;0;$j--){
		echo "+";
	}
	for($k=1;$k&amp;lt;=(2*$i)+1;$k++){
		echo "*";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a function to check if a string is a palindrome or not.


function checkPalindrome($string){
	$length=strlen($string);
	if($length&amp;gt;1){
		$mid = floor($length/2);
		$pal=true;
		for ($i=0; $i &amp;lt;=$mid; $i++) { 
			if($string[$i]!=$string[$length-($i+1)]){
				$pal=false;
				break;
			}
		}
		if($pal==false){
			return "NOT A PALINDROM";
		}else{
			return "PALINDROM";
		}
	}
}

$string ="ABCDEfEDCBA";
echo checkPalindrome($string);

 

Write a program to check whether a given number is prime or not:


function checkPrime($number){
	$check=0;
	for($i=2;$i&amp;lt;=($number/2);$i++)
	{
		if($number%$i==0){
			$check++;
			if($check==1){
			 	break ;
			}
		}
	}
	if($check==0){
		echo "$number is a Prime Number";
	}else{
		echo "$number is not a Prime Number";
	}
}

 

Write a function to test a given year is Leap Year:


function checkLeapYear($year){
	if($year%4==0){
		echo "$year is a leap year";
	}else{
   		echo "$year is not a leap year";
 	}
}

 

Write a program to swap two numbers without using any temporary variable.


function swapNumbers($a,$b){
	$a=$a+$b;
	$b=$a-$b;
	$a=$a-$b;
	echo "Now A is $a and B is $b";
}

 

Write a program to check that a given number is odd or even.


function checkOddEven($number){ 
	if($number % 2 == 0){ 
		echo "$number is EVEN"; 
	} 
	else{ 
		echo "$number is ODD"; 
	} 
} 

 

Spread the love

MVC Web Development Framework

What is Web Development Framework?

There is a huge number of server-side scripting languages, using them we can create web applications. Almost the scripts are full-fledged programming language and featured with Object Oriented Programming Systems. Popular of them are Java, PHP, Python, Ruby,Perl. At the early age of web the applications were built on conventional logic and components, are not organized or not reusable. As the next generation, web development technologies came into existence the requirement of frameworks increased.A need for such a tool was very important as they are time and cost efficient.

Now we have many frameworks with huge communities. Frameworks are the collection of basic building blocks and reusable code in an organized manner where maintenance and development both are painless processes. They implement code re-usability, inheritance, security, abstraction, accessibility, integrity, reliability, readability, maintainability in our applications. Now we are able to develop very robust applications in very less time. frameworks are enriched with various libraries and plugin. They also provide flexibility to extend the functionality of the core. Almost the framework is based on Model-View-Controller or MVC development pattern.

What is MVC?

MVC is a software architectural pattern, which provides a modular structure to an application and application is layered into Models(M), Views(V) and Controllers(C).

MODEL

Model is a layer where all the data building logic is present. This layer is abstract from direct access. We write or database queries and fetch and format data in this layer with given parameters. This layer is a central layer of all three.

VIEW

A view is a presentation layer. We see the desired results here in our browser. The user directly communicates with forms and perform actions and submit inputs. This is an end user layer where HTTP response displayed and request triggered by user actions.

CONTROLLER

A controller is an intermediate layer and create a pool between Model the data logic layer and View the representational layer. It collects user actions based on URI and parameters. Routing and reverse routing happen here.

Advantages of MVC Frameworks:

  1. Fast and quick development of complex web-applications.
  2. Collection of Plugins are available for most of the general purpose activities.
  3. Easy maintenance and debugging. Frameworks provide debugger kit , that eases the debugging process.
  4. MVC provides a modular structure to application that is why MVC based applications are flexible and robust.
  5. Most of them provide Database manipulation library, so no need to write custom and complex queries very often.
  6. Inbuilt security and migration features.
  7. Most of them come with a command-line interface to generate code-snippets and modules.
  8. They create SEO friendly URLs to easy for search engines to recognize your application urls.

What are the popular MVC framework based on PHP?

There are numerous MVC framework based on PHP. Some of them are as:
Laravel – Laravel is the most popular PHP framework with the latest release of PHP and suitable for heavy applications.It comes with Inbuilt Authentication and security features. Laravel has a powerful ORM and query builder. Laravel has a unique feature of artisan CLI tool.Blade template engine is used for presentation on view.

Zend Framework

Created by the developers of PHP.Zend Framework is a collection of professional PHP packages with more than 345 million installations. It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features. Zend Framework uses Composer as a package dependency manager; PHP Unit to test all packages; and Travis CI as a Continuous Integration service. Zend Framework also follows PHP-FIG standards and includes an implementation of PHR-7 for HTTP message interfaces (as shepherded by Matthew Weier O’Phinney, Zend Framework project lead).

CakePHP

CakePHP is a Rapid development framework written in PHP 5.6 and having a unique feature of Naming Convention. CakePHP has a powerful tool of bake console. We can create scaffolding within no time. It is suitable for Web services as well as small and heavy applications. We can use a template engine as well for the presentation layer.

Codeigniter

This is a zero-configuration framework and mostly used for small scale application. It comes with all the features of OOPS and security parameters. It is fast ,and the most flexible among others in a group. Code-igniter has wonderful and organized documentation and a huge community over the web. Codeigniter also provide the feature of HMVC and templating.

Yii

Fastest growing over the internet and popular in recent years. Featured with MVC structure and can be used for small as well as heavy applications. It handles complex WSDL services easily.

Phalcon

Phalcon is a secure and well documented MVC framework. It is suitable for any type of applications. It has implemented with very high-security level.

Spread the love

What is New In CodeIgniter 4.x?

As we all know CodeIgniter is a PHP lightweight MVC framework.

It provides us fast, flexible, and secure techniques to develop PHP based applications.

The Codeigniter 4.x alpha and beta are released but the available version is not recommended for production use.

The flexibility of Codeigniter is maintained as usual along with the advancement of compatibility with PHP 7.

 

Core Features of CodeIgniter


  • CI is an MVC framework with a small footprint.
  • Codeigniter gives exceptional performance.
  • This is an MVC  framework with zero configuration.
  • No command-line configuration setup or dependencies installation to start(Optional).
  • CI is not restricted to any naming convention or coding rules.
  • No need to learn about advanced concepts like PEAR.
  • You do not need to learn template engine rendering. 
  • Simple, Clear and easy to understand documentation.

Features of Codeigniter 4.x


  1. The earlier versions of Codeigniter are based on PHP 5.6 or lower but the Codeigniter 4 will be featured with PHP 7.2 functionality and compatibility.
  2. It required the *intl* extension of PHP installed on the server.
  3. If we would like to use CURLRequest, we will need lib curl installed.
  4. Supported databases are:
    1. MySQL (5.1+) via the MySQLi driver
    2. PostgreSQL via the Postgre driver
    3. SqLite3 via the SQLite3 driver
  5. CodeIgniter 4 can also be used with command-line programs. As per the latest trend, most of the frameworks provide CLI usability and library. Since Codeigniter 4.x the framework will also be providing CLI interfaces for different purposes.
  6. The following PHP extensions should be enabled on your server: 
    1. Php-json
    2. Php-mbstring
    3. Php-mysqlnd
    4. Php-xml
  7. If you want to use CURLRequest in your CI application, you will need to install libcurl.
  8. The framework now provides for a public folder, intended as the document root for your app
  9. Hooks in Codeigniter are a great feature in is maintained and improved as well.

How to install Codeigniter 4?



Codeigniter 4 can be installed using many methods

  • In Manual Installation, you need to download the latest release from official site and can place it in your www directory after extracting it.
  • If you want to use the composer tool you need to install the composer first and then you can install using command line. Composer will also help you to add third-party plugins in your project in the future. You can download and install the composer from this link: https://getcomposer.org/
  • You can also clone the git repository of CodeIgniter.

Directory Structure for Codeigniter 4.x



A newly installed application has six directories:

  1. application
  2. system
  3. public
  4. writable
  5. tests
  6. Docs

Application Structure

  1. The framework still has app and system folders, with the same interpretation as before
  2. The framework now provides for a public folder, intended as the document root for your app
  3. There is also a writable folder, to hold cache data, logs, and session data
  4. The application folder looks very similar to that for CI3, with some name changes, and some subfolders moved to the writable folder
  5. There is no longer a nested application/core folder

The application directory i.e. app is the source code of your application. All the stuff done by you will remain here. The default structure of the app directory is as :

/app

        /Config         Stores the configuration files

        /Controllers    Controllers determine the program flow

        /Database       Stores the database migrations and seeds files

        /Filters        Stores filter classes that can run before and after a controller

        /Helpers        Helpers store collections of standalone functions

        /Language       Multiple language support reads the language strings from here

        /Libraries      Useful classes that don’t fit in another category

        /Models         Models the database and business logic.

        /ThirdParty     ThirdParty libraries that can be used in application

        /Views          Views make up the HTML that is displayed to the client.

The above concepts will help you when you will doing any application on code igniter or you will be in CodeIgniter interview.

Spread the love