Saturday, September 10, 2022

Interview questions and answers for PHP and MySQL

1: Latest PHP version : 8.1 (Till 10 September 2022)

2: Difference between php 8 and 8.1PHP 8.1 adds support for intersection types. It's similar to union types introduced in PHP 8.0, but their intended usage is the exact opposite

3: PHP array functions:


Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_replace() Replaces the values of the first array with the values from following arrays
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an associative array in descending order, according to the value
asort() Sorts an associative array in ascending order, according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Deprecated from PHP 7.2. Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined comparison function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
4:  Method list : GET, POST, SET, REQUEST
5:How to use constant:

define("GREETING""Welcome to Blogger!");
echo GREETING;

define("GREETING""Welcome to Blogger!", true);
echo greeting;

6: .htaccess file used for:

  • URL rewriting
  • Custom error pages
  • Caching
  • Redirections
  • Blocking ip's
Code : <IfModule mod_rewrite.c>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>

6: What are the different tables present in MySQL?
  1. MyISAM
  2. Heap
  3. Merge
  4. INNO DB
  5. ISAM
7:What is SESSION ?

A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

$_SESSION["favcolor"] = "green";

8: What is cookies?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

A cookie is created with the setcookie() function.

$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day


9 : php difference between session and cookie

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.


A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)


10 : php difference between include and require


                                                include()                                            require()
The include() function does not stop the execution of the script even if any error occurs.The require() function will stop the execution of the script when an error occurs.
The include() function does not give a fatal error.The require() function gives a fatal error
The include() function is mostly used when the file is not required and the application should continue to execute its process when the file is not found.The require() function is mostly used when the file is mandatory for the application.
The include() function will only produce a warning  (E_WARNING) and the script will continue to execute.The require() will produce a fatal error (E_COMPILE_ERROR) along with the warning.
11 : Error Types:-
1:Warning Error
2:Notice Error
3:Parse Error (Syntax)
4:Fatal Error

1: Warning Error:

warning error in PHP does not stop the script from running. It only warns you that there is a problem, one that is likely to cause bigger issues in the future.

The most common causes of warning errors are:

  • Calling on an external file that does not exist in the directory
  • Wrong parameters in a function

For instance:

<?php
echo "Warning error"';
include ("external_file.php");
?>

As there is no “external_file”, the output displays a message, notifying it failed to include it. Still, it doesn’t stop executing the script.

2: Notice Error:

Notice errors are minor errors. They are similar to warning errors, as they also don’t stop code execution. Often, the system is uncertain whether it’s an actual error or regular code. Notice errors usually occur if the script needs access to an undefined variable.

Example:

<?php
$a="Defined error";
echo "Notice error";
echo $b;
?>

In the script above, we defined a variable ($a), but called on an undefined variable ($b). PHP executes the script but with a notice error message telling you the variable is not defined.

3:Parse Error (Syntax)

Parse errors are caused by misused or missing symbols in a syntax. The compiler catches the error and terminates the script.

Parse errors are caused by:

  • Unclosed brackets or quotes
  • Missing or extra semicolons or parentheses
  • Misspellings

For example, the following script would stop execution and signal a parse error:

<?php
echo "Red";
echo "Blue";
echo "Green"
?>

It is unable to execute because of the missing semicolon in the third line.

4: Fatal Error:-

Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.

There are three (3) types of fatal errors:

  1. Startup fatal error (when the system can’t run the code at installation)
  2. Compile time fatal error (when a programmer tries to use nonexistent data)
  3. Runtime fatal error (happens while the program is running, causing the code to stop working completely)

For instance, the following script would result in a fatal error:

<?php
function sub()
{
$sub=6-1;
echo "The sub= ".$sub;
}
div();
?>

The output tells you why it is unable to compile

12: What is the difference between the functions unlink() and unset()?
unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.
13: Why we use $_REQUEST variable?
We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable
14: What is the difference between isset and empty?
isset: This variable is used to handle functions and checked a variable is set even through it is empty.
empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.
15: What is the use of explode() function ?
This function is used to split a string into an array. Syntax : array explode( string $delimiter , string $string [, int $limit ] );

16:How to start displaying errors in PHP application?
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(E_ALL);
OR Add following code in .htacess
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
17: What are the various constants predefined in PHP?

PHP consists of many constants, and following are some of the widely used ones:

  • _METHOD_: Represents the class name
  • _CLASS_: Returns the class name
  • _FUNCTION_: Denotes the function name
  • _LINE_: Denotes the working line number
  • _FILE_: Represents the path and the file name
18: What is the use of the final class and the final method in PHP?

The ‘final’ keyword, if present in a declaration, denotes that the current method does not support overriding by other classes. This is used when there is a requirement to create an immutable class.

Note: Properties cannot be declared as final. It is only methods and classes that get to be final.

19: What is the use of constructors and destructors in PHP?

Constructors are used in PHP as they allow you to pass parameters when creating a new object easily. This is used to initialize the variables for the particular object in consideration.

Destructors are methods used to destroy an object. Both of these are special methods provided in PHP for you to perform complex procedures using a single step.

20: Differentiate between an indexed array and an associative array.

Indexed arrays have elements that contain a numerical index value.

Example: $color=array("red","green","blue");

Here, red is at index 0, green at 1, and blue at 2.

Associative arrays, on the other hand, hold elements with string indices as shown below:

Example: $salary=array("Jacob"=>"20000","John"=>"44000","Josh"=>"60000");
21 : What are magic methods?

Magic methods are member functions that are available to all the instances of a class. Magic methods always start with ‘__’, for example, __construct(). All magic methods need to be declared as public.

To use a method, it should be defined within the class or the program scope. Various magic methods used in PHP5 are:

  • __construct()
  • __destruct()
  • __set()
  • __get()
  • __call()
  • __toString()
  • __sleep()
  • __wakeup()
  • __isset()
  • __unset()
  • __autoload()
  • __clone()

22: What are Procedures in MySQL?
Procedures (or stored procedures) are subprograms, just like in a regular language, embedded in the database. A stored procedure consists of a name, SQL statement(s) and parameters. It utilises the caching in MySQL and hence saves time and memory, just like the prepared statements. 

23: What is a trigger in MySQL?
A trigger is a table-associated database object in MySQL. It is activated when a specified action takes place. 
A trigger can be invoked after or before the event takes place. It can be used on INSERT, DELETE, and UPDATE. It uses the respective syntax to define the triggers. For example, BEFORE INSERT, AFTER DELETE, etc.
24: What is a LIKE statement? Explain % and _ in LIKE.
While using filters in commands like SELECT, UPDATE, and DELETE, conditions might require a pattern to detect. LIKE is used to do just that. LIKE has two wildcard characters, namely % (percentage) and _ (underscore). Percentage(%) matches a string of characters, while underscore matches a single character.

For example, %t will detect trees and tea both. However, _t will only detect one extra character, i.e., strings like ti or te.

25: How does DISTINCT work in MySQL?
DISTINCT is used to avoid the problem of duplicity while fetching the results of a particular query. DISTINCT is used to make sure the results do not contain repeated values. DISTINCT can be used with the SELECT clause. Here is the syntax for it:

SELECT DISTINCT something FROM tablename;

26: What are some of the common MySQL commands?
CommandAction
ALTERTo alter a database or table
BACKUPTo back-up a table
\cTo cancel Input
CREATETo create a database
DELETETo delete a row from a table
DESCRIBETo describe a table's columns
DROPTo delete a database or table
EXIT(ctrl+c)To exit
GRANTTo change user privileges
HELP (\h, \?)Display help
INSERTInsert data
LOCKLock table(s)
QUIT(\q)Same as EXIT
RENAMERename a Table
SHOWList details about an object
SOURCEExecute a file
STATUS (\s)Display the current status
TRUNCATEEmpty a table
UNLOCKUnlock table(s)
UPDATEUpdate an existing record
USEUse a database
27 : What are MySQL “Views”?

In MySQL, a view consists of a set of rows that is returned if a particular query is executed. This is also known as a ‘virtual table’. Views make it easy to retrieve the way of making the query available via an alias. 
The advantages of views are:

  • Simplicity
  • Security
  • Maintainability

28: What are MySQL Triggers?

A trigger is a task that executes in response to some predefined database event, such as after a new row is added to a particular table. Specifically, this event involves inserting, modifying, or deleting table data, and the task can occur either prior to or immediately following any such event.

Triggers have many purposes, including:

  • Audit Trails
  • Validation
  • Referential integrity enforcement
29: How many Triggers are possible in MySQL?
There are six Triggers allowed to use in the MySQL database:
  • Before Insert
  • After Insert
  • Before Update
  • After Update
  • Before Delete
  • After Delete

30: How to find Nth highest salary from a table

Employee 

ename sal 
A23000
B31000
C24500
D35000
E28500
F31500
G39800
H51000
I39800

Query : 
select * from(
select ename, sal, dense_rank() 
over(order by sal desc)r from Employee) 
where r=&n;

To find to the 2nd highest sal set n = 2
To find 3rd highest sal set n = 3 and so on.
31 : Difference between DELETE, DROP and TRUNCATE

1. DELETE : 

Basically, it is a Data Manipulation Language Command (DML). It is used to delete one or more tuples of a table. With the help of the “DELETE” command, we can either delete all the rows in one go or can delete rows one by one. i.e., we can use it as per the requirement or the condition using the Where clause. It is comparatively slower than the TRUNCATE command. The TRUNCATE command does not remove the structure of the table.

  • SYNTAX – 
    If we want to delete all the rows of the table:
DELETE from;
  • SYNTAX – 
    If we want to delete the row of the table as per the condition then we use the WHERE clause,
DELETE from  WHERE  ;

Note – Here we can use the “ROLLBACK” command to restore the tuple because it does not auto-commit.

2. DROP : 

It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes the named elements of the schema. By using this command the existence of the whole table is finished or say lost. 

  • SYNTAX – 
    If we want to drop the table:
DROP table ;

Note – Here we can’t restore the table by using the “ROLLBACK” command because it auto commits.

3. TRUNCATE : 

It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table) in one go. With the help of the “TRUNCATE” command, we can’t delete the single row as here WHERE clause is not used. By using this command the existence of all the rows of the table is lost. It is comparatively faster than the delete command as it deletes all the rows fastly. 

  • SYNTAX – 
    If we want to use truncate :
TRUNCATE;

Note – Here we can’t restore the tuples of the table by using the “ROLLBACK” command.

32 : What are the differences between die()and exit() functions in PHP? 
There's no difference - they are the same. The only advantage of choosing die() over exit(), might be the time you spare on typing an extra letter.


33 : What are the main differences between const vs define
The fundamental difference between const vs define is that const defines constants at compile time, whereas define defines them at run time. Define can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.

Unless you need any type of conditional or expressional definition, use consts instead of define()- simply for the sake of readability!


34 : What is the difference between var_dump() and print_r()?
  • The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

  • The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Consider:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj)will display below output in the screen:

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)
35 : What's the difference between isset() and array_key_exists()?
  • array_key_exists will tell you if a key exists in an array and complains when $a does not exist.
  • isset will only return true if the key/variable exists and is not null. isset doesn't complain when $a does not exist.

Consider:

$a = array('key1' => 'Foo Bar', 'key2' => null);

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true
36 : When should I use require vs include?

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

37 : Explain the difference between exec() vs system() vs passthru()?

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.
38 : What is the difference between PDO's query() vs execute()?
  • query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
  • execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times.

Best practice is to stick with prepared statements and execute for increased security. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution.

No comments:

Post a Comment