Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Sunday, February 21, 2021

A few questions worth noticing about MySQL

 

1. What is MySQL? 

MySQL is an open source DBMS which is built, supported and distributed by MySQL AB (now acquired by Oracle)

2. What are the technical features and technical specifications of MySQL? 

MySQL database software is a client or server system which includes features:

  • Multithreaded SQL server supporting various client programs and libraries
  • Different backend
  • Wide range of application programming interfaces and
  • Administrative tools.

And technical specifications:

  • Flexible structure
  • High performance
  • Manageable and easy to use
  • Replication and high availability
  • Security and storage management
  • Drivers
  • Graphical Tools
  • MySQL Enterprise Monitor
  • MySQL Enterprise Security
  • JSON Support
  • Replication & High-Availability
  • Manageability and Ease of Use
  • OLTP and Transactions
  • Geo-Spatial Support

3. Why do we use the MySQL database server?

MySQL database server is reliable, fast and very easy to use.  This software can be downloaded as freeware and can be downloaded from the internet.

4. What are Heap tables?

HEAP tables are present in memory and they are used for high speed storage on temporary

basis.

• BLOB or TEXT fields are not allowed

• Only comparison operators can be used =, <,>, = >,=<

• AUTO_INCREMENT is not supported by HEAP tables

• Indexes should be NOT NULL

5. What is the default port for MySQL Server?

The default port for MySQL server is 3306.

6. What are the advantages of MySQL when compared with Oracle? 

  • MySQL is open source software which is available at any time and has no cost involved.
  • MySQL is portable
  • GUI with command prompt.
  • Administration is supported using MySQL Query Browser

7. Differentiate between FLOAT and DOUBLE? 

Following are differences for FLOAT and DOUBLE:

• Floating point numbers are stored in FLOAT with eight place accuracy and it has four bytes.

• Floating point numbers are stored in DOUBLE with accuracy of 18 places and it has eight bytes.

8. In which language MySQL has been written?

MySQL is written in C and C++, and its SQL parser is written in yacc.

9. How to represent ENUMs and SETs internally? 

ENUMs and SETs are used to represent powers of two because of storage optimizations.

10. What is the usage of ENUMs in MySQL?

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

 Create table size(name ENUM('Small', 'Medium','Large'); 

11. Define REGEXP? 

REGEXP is a pattern match in which  matches pattern anywhere in the search value.

12. Difference between CHAR and VARCHAR? 


Following are the differences between CHAR and VARCHAR:

  • CHAR and VARCHAR types differ in storage and retrieval
  • CHAR column length is fixed to the length that is declared while creating table. The length value ranges from 1 and 255
  • When CHAR values are stored then they are right padded using spaces to specific length. Trailing spaces are removed when CHAR values are retrieved.

13. Give string types available for column?

The string types are:

  • SET
  • BLOB
  • ENUM
  • CHAR
  • TEXT
  • VARCHAR

14. How to get current MySQL version?

 SELECT VERSION ();

is used to get the current version of MySQL.

15. What storage engines are used in MySQL? 

Storage engines are called table types and data is stored in files using various techniques.

Technique involves:

  • Storage mechanism
  • Locking levels
  • Indexing
  • Capabilities and functions.

16. What are the drivers in MySQL?

Following are the drivers available in MySQL:

  • PHP Driver
  • JDBC Driver
  • ODBC Driver
  • C WRAPPER
  • PYTHON Driver
  • PERL Driver
  • RUBY Driver
  • CAP11PHP Driver
  • Ado.net5.mxj

17. What does a TIMESTAMP do on UPDATE CURRENT_TIMESTAMP data type?

TIMESTAMP column is updated with Zero when the table is created.  UPDATE CURRENT_TIMESTAMP modifier updates the timestamp field to current time whenever there is a change in other fields of the table.

18. What is the difference between primary key and candidate key?

Every row of a table is identified uniquely by primary key. There is only one primary key for a table.

Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.

19. How do you login to MySql using Unix shell?

We can login through this command:

# [mysql dir]/bin/mysql -h hostname -u <UserName> -p <password>

20. What does myisamchk do?

It compress the MyISAM tables, which reduces their disk or memory usage.

21. How do you control the max size of a HEAP table?

Maximum size of Heal table can be controlled by MySQL config variable called max_heap_table_size.

22. What is the difference between MyISAM Static and MyISAM Dynamic?

In MyISAM static all the fields will have fixed width. The Dynamic MyISAM table will have fields like TEXT, BLOB, etc. to accommodate the data types with various lengths.

MyISAM Static would be easier to restore in case of corruption.

23. What are federated tables?

Federated tables which allow access to the tables located on other databases on other servers.

24. What, if a table has one column defined as TIMESTAMP?

Timestamp field gets the current timestamp whenever the row gets altered.

25. What happens when the column is set to AUTO INCREMENT and if you reach maximum value in the table?

It stops incrementing. Any further inserts are going to produce an error, since the key has been used already.

26. How can we find out which auto increment was assigned on Last insert?

LAST_INSERT_ID will return the last value assigned by Auto_increment and it is not required to specify the table name.

27. How can you see all indexes defined for a table?

Indexes are defined for the table by:

SHOW INDEX FROM <tablename>;

28. What do you mean by % and _ in the LIKE statement?

% corresponds to 0 or more characters, _ is exactly one character in the LIKE statement.

29. How can we convert between Unix & MySQL timestamps?

UNIX_TIMESTAMP is the command which converts from MySQL timestamp to Unix timestamp

FROM_UNIXTIME is the command which converts from Unix timestamp to MySQL timestamp.

30. What are the column comparisons operators?

The = , <>, <=, <, >=, >,<<,>>, <=>, AND, OR, or LIKE operators are used in column comparisons in SELECT statements.

31. How can we get the number of rows affected by query?

Number of rows can be obtained by

 SELECT COUNT (user_id) FROM users;

32.  Is Mysql query is case sensitive?

No.

SELECT VERSION(), CURRENT_DATE;SeLect version(), current_date;seleCt vErSiOn(), current_DATE; 

All these examples are same. It is not case sensitive.

33. What is the difference between the LIKE and REGEXP operators?  

LIKE and REGEXP operators are used to express with ^ and %.

SELECT * FROM employee WHERE emp_name REGEXP "^b";SELECT * FROM employee WHERE emp_name LIKE "%b"; 

34. What is the difference between BLOB AND TEXT?

A BLOB is a binary large object that can hold a variable amount of data. There are four types of BLOB –

  • TINYBLOB
  • BLOB
  • MEDIUMBLOB and
  • LONGBLOB

They all differ only in the maximum length of the values they can hold.

A TEXT is a case-insensitive BLOB. The four TEXT types

  • TINYTEXT
  • TEXT
  • MEDIUMTEXT and
  • LONGTEXT

They all correspond to the four BLOB types and have the same maximum lengths and storage requirements.

The only difference between BLOB and TEXT types is that sorting and comparison is performed in case-sensitive for BLOB values and case-insensitive for TEXT values.

35. What is the difference between mysql_fetch_array and mysql_fetch_object?

Following are the differences between mysql_fetch_array and mysql_fetch_object:

mysql_fetch_array() -Returns a result row as an associated array or a regular array from database.

mysql_fetch_object –  Returns a result row as object from database.

36. How can we run batch mode in mysql?

Following commands are used to run in batch mode:

 mysql ;mysql mysql.out

37. Where MyISAM table will be stored and also give their formats of storage?

Each MyISAM table is stored on disk in three formats:

  • The ‘.frm’ file stores the table definition
  • The data file has a ‘.MYD’ (MYData) extension
  • The index file has a ‘.MYI’ (MYIndex) extension

38. What are the different tables present in MySQL?

Total 5 types of tables are present:

  • MyISAM
  • Heap
  • Merge
  • INNO DB
  • ISAM

MyISAM is the default storage engine as of MySQL .

39. What is ISAM?

ISAM  is abbreviated as Indexed Sequential Access Method.It was developed by IBM to store and retrieve data on secondary storage systems like tapes.

40. What is InnoDB?

lnnoDB is a transaction safe storage engine developed by Innobase Oy which is a Oracle Corporation now.

41. How MySQL Optimizes DISTINCT?

DISTINCT is converted to a GROUP BY on all columns and it will be combined with ORDER BY clause.

 SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;

42. How to enter Characters as HEX Numbers?

If you want to enter characters as HEX numbers, you can enter HEX numbers with single quotes and a prefix of (X), or just prefix HEX numbers with (Ox).

A HEX number string will be automatically converted into a character string, if the expression context is a string.

43. How to display top 50 rows?

In MySql, top 50 rows are displayed by using this following query:

 SELECT * FROMLIMIT 0,50;

44. How many columns can be used for creating Index?

Maximum of 16 indexed columns can be created for any standard table.

45. What is the different between NOW() and CURRENT_DATE()?

NOW () command is used to show current year,month,date with hours,minutes and seconds.

CURRENT_DATE() shows current year,month and date only.

46. What are the objects can be created using CREATE statement?

Following objects are created using CREATE statement:

  • DATABASE
  • EVENT
  • FUNCTION
  • INDEX
  • PROCEDURE
  • TABLE
  • TRIGGER
  • USER
  • VIEW

47. How many TRIGGERS are allowed in MySql table?

SIX triggers are allowed in MySql table. They are as follows:

  • BEFORE INSERT
  • AFTER INSERT
  • BEFORE UPDATE
  • AFTER UPDATE
  • BEFORE DELETE and
  • AFTER DELETE

48. What are the nonstandard string types?

Following are Non-Standard string types:

  • TINYTEXT
  • TEXT
  • MEDIUMTEXT
  • LONGTEXT

49. What are all the Common SQL Function?

CONCAT(A, B) – Concatenates two string values to create a single string output. Often used to combine two or more fields into one single field.

FORMAT(X, D) – Formats the number X to D significant digits.

CURRDATE(), CURRTIME() – Returns the current date or time.

NOW() – Returns the current date and time as one value.

MONTH(), DAY(), YEAR(), WEEK(), WEEKDAY() – Extracts the given data from a date value.

HOUR(), MINUTE(), SECOND() – Extracts the given data from a time value.

DATEDIFF(A, B) – Determines the difference between two dates and it is commonly used to calculate age

SUBTIMES(A, B) – Determines the difference between two times.

FROMDAYS(INT) – Converts an integer number of days into a date value.

50. Explain Access Control Lists.

An ACL (Access Control List) is a list of permissions that is associated with an object. This list is the basis for MySQL server’s security model and it helps in troubleshooting problems like users not being able to connect.

MySQL keeps the ACLs (also called grant tables) cached in memory. When a user tries to authenticate or run a command, MySQL checks the authentication information and permissions against the ACLs, in a predetermined order.

51. Differentiate CHAR_LENGTH and LENGTH?

CHAR_LENGTH  is character count whereas the LENGTH is byte count. The numbers are same for Latin characters but they are different for Unicode and other encodings.

52. What is the difference between TRUNCATE and DELETE in MySQL?

TRUNCATE is a DDL command, DELETE is a DML command.

It is not possible to use Where command with TRUNCATE but you can use it with DELETE command.

TRUNCATE cannot be used with indexed views whereas DELETE can be used with indexed views.

The DELETE command is used to delete data from a table. It only deletes the rows of data from the table while, truncate is very dangerous command and should be used carefully because it deletes every row permanently from a table.

53. How to get the current date in MySQL?

To get current date, use the following syntax:

SELECT CURRENT_DATE();    

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

Let us take a table named the employee.

To find Nth highest salary is:

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

if you want to find 3rd largest salary:

select distinct(salary)from employee order by salary desc limit 2,1

55. What is the difference between NOW() and CURRENT_DATE()?

NOW() command is used to show current year, month, date with hours, minutes and seconds while CURRENT_DATE() shows the current year with month and date only.

56. Write a query to display current date and time?

If you want to display current date and time, use –

SELECT NOW();

If you want to display current date only, use:

SELECT CURRENT_DATE();

57. How can you validate emails using a single query?

To validate emails you can use the function of the regular expression (REGEXP_LIKE). Consider the below query.

 SELECT
Email
FROM
Employee
where NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);

58. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition operator is used to check for values contained in a specific set of values.

Example of BETWEEN:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;

Example of IN:

SELECT * FROM students where ROLL_NO IN (8,15,25);

59. How can you calculate the sum of any column of a table?

SELECT SUM(price) as total FROM products;

60. What IFNULL() statement is used for in MySQL?

The Query in MySQL can be written precisely using IFNULL() statement. The IFNULL() statement test its first argument and returns if it’s not NULL, or returns its second argument, otherwise.

mysql> SELECT name, IFNULL(id,'Unknown') AS 'id' FROM taxpayer;

+---------+---------+ 
| name 	  | id      | 
+---------+---------+ 
| bernina | 198-48  | 
| bertha  | Unknown | 
| ben     | Unknown | 
| bill    | 475-83  | 
+---------+---------+

61. How will you export tables as an XML file in MySQL?

We use ‘-e‘ (export) option to export MySQL table or the whole database into an XML file. With large tables we may need to implement it manually but for small tables, applications like phpMyAdmin can do the job.

A native command of MySQL can do it.

mysql -u USER_NAME –xml -e 'SELECT * FROM table_name' > table_name.xml

 

 

Saturday, February 20, 2021

Just a few things in PHP that need everyone to go through

 

1) What is PHP?

PHP stands for Hypertext Preprocessor. It is an open-source server-side scripting language that is widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.


2) What is PEAR in PHP?

PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries.

It also provides a command-line interface to install “packages” automatically.


3) Who is known as the father of PHP?

Rasmus Lerdorf


4) What was the old name of PHP?

The old name of PHP was the Personal Home Page.


5) Explain the difference b/w static and dynamic websites?

In static websitescontent can’t be changed after running the script. You can’t change anything on the site. It is predefined.

In dynamic websites, the content of the script can be changed at the run time. Its content is regenerated every time a user visits or reload. Google, yahoo and every search engine is an example of a dynamic website.


6) What is the name of the scripting engine in PHP?

The scripting engine that powers PHP is called Zend Engine 2.


7) Explain the difference between PHP4 and PHP5.

PHP4 doesn’t support oops concept and uses Zend Engine 1.

PHP5 supports oops concept and uses Zend Engine 2.


8) What are the popular Content Management Systems (CMS) in PHP?

  • WordPress: WordPress is a free and open-source content management system (CMS) based on PHP & MySQL. It includes a plug-in architecture and template system. It is mostly connected with blogging but supports another kind of web content, containing more traditional mailing lists and forums, media displays, and online stores.
  • Joomla: Joomla is a free and open-source content management system (CMS) for distributing web content, created by Open Source Matters, Inc. It is based on a model-view-controller web application framework that can be used independently of the CMS.
  • Magento: Magento is an open source E-trade programming, made by Varien Inc., which is valuable for online business. It has a flexible measured design and is versatile with many control alternatives that are useful for clients. Magento utilizes E-trade stage which offers organization extreme E-business arrangements and extensive support network.
  • Drupal: Drupal is a CMS platform developed in PHP and distributed under the GNU (General Public License).

9) What are the popular frameworks in PHP?

  • Laravel
  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework etc.

10) Which programming language does PHP resemble to?

PHP has borrowed its syntax from Perl and C.


11) List some of the features of PHP7.

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator (??)
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Closure::call method
  • Group use declaration
  • Generator return expressions
  • Generator delegation
  • Space ship operator

12) What is “echo” in PHP?

PHP echo output one or more string. It is a language construct not a function. So the use of parentheses is not required. But if you want to pass more than one parameter to echo, the use of parentheses is required.

Syntax:

  1. void echo ( string $arg1 [, string $… ] )  

13) What is “print” in PHP?

PHP print output a string. It is a language construct not a function. So the use of parentheses is not required with the argument list. Unlike echo, it always returns 1.

Syntax:

  1. int print ( string $arg)  

14) What is the difference between “echo” and “print” in PHP?

Echo can output one or more string but print can only output one string and always returns 1.

The echo is faster than print because it does not return any value.


15) How a variable is declared in PHP?

 A PHP variable is the name of the memory location that holds data. It is a temporary storage.

Syntax:

  1. $variableName=value;  

16) What is the difference between $message and $$message?

$message stores variable data while $$message is used to store variable of variables.

$message stores fixed data whereas the data stored in $$message may be changed dynamically.


17) What are the ways to define a constant in PHP?

PHP constants are name or identifier that can’t be changed during execution of the script. PHP constants are defined in two ways:

  • Using define() function
  • Using const() function

18) What are magic constants in PHP?

PHP magic constants are predefined constants, which change based on their use. They start with a double underscore (__) and end with a double underscore (__).


19) How many data types are there in PHP?

PHP data types are used to hold different types of data or values. There are 8 primitive data types which are further categorized in 3 types:

  • Scalar types
  • Compound types
  • Special types

20) How to do single and multi line comment in PHP?

PHP single line comment is made in two ways:

  • Using // (C++ style single line comment)
  • Using # (Unix Shell style single line comment)

PHP multi-line comment is made by enclosing all lines within.


21) What are the different loops in PHP?

For, while, do-while and for each.

22) What is the use of count() function in PHP?

The PHP count() function is used to count total elements in the array, or something an object.


23) What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this function.


24) What does isset() function?

The isset() function checks if the variable is defined and not null.


25) Explain PHP parameterized functions.

PHP parameterized functions are functions with parameters. You can pass any number of parameters inside a function. These given parameters act as variables inside your function. They are specified inside the parentheses, after the function name. Output depends upon dynamic values passed as parameters into the function.


26) Explain PHP variable-length argument function

PHP supports variable-length argument function. It means you can pass 0, 1 or n number of arguments in function. To do this, you need to use 3 ellipses (dots) before the argument name. The 3 dot concept is implemented for variable-length argument since PHP 5.6.


27) Explain PHP variable length argument function.

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments.


28) What is the array in PHP?

An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and values. It saves the collection of the data type.

29) How many types of the array are there in PHP?

There are three types of the array in PHP:

  1. Indexed array: an array with a numeric key.
  2. Associative array: an array where each key has its specific value.
  3. Multidimensional array: an array containing one or more arrays within itself.

30) Explain some of the PHP array functions?

There are many array functions in PHP:

  • array()
  • array_change_key_case()
  • array_chunk()
  • count()
  • sort()
  • array_reverse()
  • array_search()
  • array_intersect()

31) What is the difference between indexed and associative array?

The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For example:

$season=array("summer","winter","spring","autumn");    

The associative array holds elements with name. For example:

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    

32) How to get the length of string?

The strlen() function is used to get the length of the string.


33) Explain some of the PHP string functions?

There are many array functions in PHP:

  • strtolower()
  • strtoupper()
  • ucfirst()
  • lcfirst()
  • ucwords()
  • strrev()
  • strlen()

34) What are the methods to submit the form in PHP?

There are two methods GET and POST.


35) How can you submit a form without a submit button?

You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.


36) What are the ways to include file in PHP?

PHP allows you to include file so that page content can be reused again. There are two ways to add the file in PHP.

  1. include
  2. require

37) Differentiate between require and include?

Require and include both are used to include a file, but if data is not found include sends warning whereas require sends Fatal error.


38) Explain setcookie() function in PHP?

PHP setcookie() function is used to set cookie with HTTP response. Once the cookie is set, you can access it by $_COOKIE superglobal variable.

Syntax:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path     
 [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )     

39) How can you retrieve a cookie value?

echo $_COOKIE ["user"];  

40) What is a session?

PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which is known as session.

Sessions generally store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same user.

Simply, it maintains data of an user (browser).


41) What is the method to register a variable into a session?

  1. <?php  
  2. Session_register($ur_session_var);  
  3. ?>  

42) What is $_SESSION in PHP?

A session creates a file in a temporary directory on the server where registered session variables and their session id are stored. This data will be available to all pages on the site amid that visit.

The area of the temporary record is controlled by a setting in the php.ini document called session.save_path.

At the point when a session is begun following things happen –

  1. PHP first makes two duplicates of one of a kind session id for that particular session of the client which is an arbitrary string of 32 hexadecimal numbers, for example, 3c7foj34c3jjhkyepop2fc937e3443.
  2. One copy of unique session id automatically sent to the user?s computer for the sake of synchronization in future ahead, and one copy is being maintained at server side till the session is running.
  3. Whenever you want to access the page of website or web app, then session id of the current user will be associated with the HTTP header, and that will be compared by the session id which is being maintained at the server. After completing the comparison process, you can easily access the page of the website or web app
  4. A session ends when the user closes the browser, or after leaving the site, the server will terminate the session after a predetermined period, commonly 30 minutes duration.

43) What is PHP session_start() and session_destroy() function?

PHP session_start() function is used to start the session. It starts new or resumes the current session. It returns the current session if the session is created already. If the session is not available, it creates and returns new sessions.


44) What is the difference between session and cookie?

The main difference between session and cookie is that cookies are stored on user’s computer in the text file format while sessions are stored on the server side.

Cookies can’t hold multiple variables, on the other hand, Session can hold multiple variables.

You can manually set an expiry for a cookie, while session only remains active as long as browser is open.


45) Write syntax to open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.

Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  

46) How to read a file in PHP?

PHP provides various functions to read data from the file. Different functions allow you to read all file data, read data line by line, and read data character by character.

PHP file read functions are given below:

  • fread()
  • fgets()
  • fgetc()

47) How to write in a file in PHP?

PHP fwrite() and fputs() functions are used to write data into file. To write data into a file, you need to use w, r+, w+, x, x+, c or c+ mode.


48) How to delete file in PHP?

The unlink() function is used to delete a file in PHP.

bool unlink (string $filename)      

49) What is the method to execute a PHP script from the command line?

You should just run the PHP command line interface (CLI) and specify the file name of the script to be executed as follows.


50) How to upload file in PHP?

The move_uploaded_file() function is used to upload file in PHP.

bool move_uploaded_file ( string $filename , string $destination )    

51) How to download file in PHP?

The readfile() function is used to download the file in PHP.

int readfile ( string $filename )     


52) How can you send email in PHP?

The mail() function is used to send email in PHP.

bool mail($to,$subject,$message,$header);    

53) How do you connect MySQL database with PHP?

There are two methods to connect MySQL database with PHP. Procedural and object-oriented style.


54) How to create connection in PHP?

The mysqli_connect() function is used to create a connection in PHP.

resource mysqli_connect (server, username, password)       

55) How to create database connection and query in PHP?

Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use the following 2 alternatives.

  • mysqli_query()
  • PDO::_query()

56) How can we increase execution time of a PHP script?

By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the script and returns an error.

You can change the script run time by changing the max_execution_time directive in the php.ini file.

When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(), then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited time.


57) What are the different types of errors in PHP?

There are 3 types of error in PHP.

  1. Notices:These are non-critical errors. These errors are not displayed to the users.
  2. Warnings:These are more serious errors, but they do not result in script termination. By default, these errors are displayed to the user.
  3. Fatal Errors:These are the most critical errors. These errors may cause due to immediate termination of script.

58) How to stop the execution of PHP script?

The exit() function is used to stop the execution of PHP script.


59) What are the encryption functions in PHP?

CRYPT() and MD5()


60) What is htaccess in PHP?

The .htaccess is a configuration file on Apache server. You can change configuration settings using directives in Apache configuration files like .htaccess and httpd.conf.


61) Explain PHP explode() function.

The PHP explode() function breaks a string into an array.


62) Explain PHP split() function.

The PHP split() function splits string into an array by regular expression.


63) How can we get IP address of a client in PHP?

  1. $_SERVER[“REMOTE_ADDR”];  

64) What is the meaning of a Persistent Cookie?

A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.


65) What is the use of the function ‘imagetypes()’?

imagetypes() gives the image format and types supported by the current version of GD-PHP.


66) What are include() and require() functions?

The Include() function is used to put data of one PHP file into another PHP file. If errors occur, then the include() function produces a warning but does not stop the execution of the script, and it will continue to execute.

The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors, then the require() function produces a warning and a fatal error and stops the script.


67) What is Cookies? How to create cookies in PHP?

A cookie is used to identify a user. A cookie is a little record that the server installs on the client’s Computer. Each time a similar PC asks for a page with a program, it will send the cookie as well. With PHP, you can both make and recover cookie value.

Some important points regarding Cookies:

  1. Cookies maintain the session id generated at the back end after verifying the user’s identity in encrypted form, and it must reside in the browser of the machine
  2. You can store only string values not object because you can’t access any object across the website or web apps
  3. Scope: – Multiple pages.
  4. By default, cookies are temporary and transitory cookie saves in the browser only.
  5. By default, cookies are URL particular means Gmail isn’t supported in Yahoo and the vice versa.
  6. Per site 20 cookies can be created in one website or web app
  7. The Initial size of the cookie is 50 bytes.
  8. The Maximum size of the cookie is 4096 bytes.

68) What is the Importance of Parser in PHP?

PHP parser parses the PHP developed website from the opening to the closing tag. Tags indicate that from where PHP code is being started and ended. In other words, opening and closing tags decide the scope of PHP scripting syntax of closing tag in PHP

<?php syntax of opening tag in PHP
?> syntax of closing tag in PHP


69) How can we create a database using PHP and MySQL?

The necessary steps to create a MySQL database using PHP are:

  • Establish a connection to MySQL server from your PHP script.
  • If the connection is successful, write a SQL query to create a database and store it in a string variable.
  • Execute the query.

Logical PHP interview questions and answers

1) Find 2nd largest value in an array.

1
2
3
4
5
<?php
$numbers = array(5, 3, 7, 9, 6, 8);
sort($numbers);
echo $numbers[count($numbers) - 2];   //Output: 8
?>

2) Find a word in a string and replace it.

1
2
3
4
5
<?php
$string = "Tutsmake has good blog for PHP programming.";
$newString = str_replace("good", "nice", $string);
echo $newString;    //Output: Tutsmake has nice blog for PHP programming."
?>

3) Find a position of a word in a string.

1
2
3
4
5
<?php
$string = "Tutsmake has good blog for PHP programming.";
$pos = strpos($string, "good");
echo $pos; //Output: 12
?>

4) How to display first 100 characters of a paragraph.

1
2
3
4
5
6
<?php
$paragraph = "OOPs is a powerful software development concept and it always insists to minimize, reuse and better management of code. Inheritance is one of the powerful features of OOPs which provides re-usability of code. Traits which is a new feature introduce in PHP 5.4. The concept of traits added some extra feature in single inheritance.";
$substring = substr($paragraph, 0, 100);
echo $substring;
//Output: OOPs is a powerful software development concept and it always insists to minimize, reuse and better
?>

5) Find the last 4 letters of the string.

1
2
3
4
5
<?php
$string = "Tutsmake has good blog for PHP programming";
$substring = substr($string, -4);
echo $substring; //Output: ming
?>

6) Extract “good blog” from in given the below string.

1
2
3
4
5
6
<?php
$string = "Tutsmake has good blog for PHP programming.";
$extractWord = "good blog";
$substring = substr($string, strpos($string, $extractWord), strlen($extractWord));
echo $substring; //Output: good blog
?>

7) Find the index of any element in an array.

1
2
3
4
5
<?php
$numbers = array(5, 3, 7, 9, 6, 8);
echo array_search(7, $numbers);
//Output: 2
?>

8) What will be output of below code and why?

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$string = "Tutsmake has good blog for PHP programming.";
$substr = "Tutsmake";
if(strpos($string, $substr))
{
                echo "found";
}
else
{
                echo "not found";
}
?>

Output will be “not found” because strpos($string, $substr) returns 0 as position and this is treated as false in IF condition. So the right code below.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$string = "Tutsmake has good blog for PHP programming.";
$substr = "Tutsmake";
if(strpos($string, $substr) !== false)
{
                echo "found";
}
else
{
                echo "not found";
}
?>

9) How to remove first two elements from an array.

1
2
3
4
5
6
<?php
$alphabats = array("a", "b", "c", "d", "e");
$output = array_slice($alphabats, 2);
print_r($output);
//Output Array ( [0] => c [1] => d [2] => e )
?>

10) How to remove two elements from middle in below array.

$colors = array(“red”, “green”, “blue”, “yellow”);

1
2
3
4
5
6
<?php
$colors = array("red", "green", "blue", "yellow");
array_splice($colors, 1, -1);
print_r($colors);
//Output: Array ( [0] => red [1] => yellow )
?>

11) How to remove last element and insert two new elements in below array.

$colors = array(“red”, “green”, “blue”, “yellow”);

$lastColors = array(“orange”, “maroon”);

1
2
3
4
5
6
<?php
$colors = array("red", "green", "blue", "yellow");
array_splice($colors, -1, 1, $lastColors);
print_r($colors);
//Output: Array ( [0] => red [1] => green [2] => blue [3] => orange [4] => maroon )
?>

12) Check element in below array is an array or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$colors = array("red", "green", array("orange", "maroon"), "blue", "yellow", array("purple", "brown"));
foreach($colors as $c)
{
    if(is_array($c))
    {
        echo "This element is an array.";
    }
    else
    {
        echo "This element is not an array.";
    }
}
?>

13) Convert any string into an array.

1
2
3
4
5
6
7
8
9
10
<?php
$name = "sachin tendulkar";
$nameArray = array();
for($i = 0; $i<strlen($name); $i++)
{
    $nameArray[] = $name[$i];
}
print_r($nameArray);
//Output: Array ( [0] => s [1] => a [2] => c [3] => h [4] => i [5] => n [6] => [7] => t [8] => e [9] => n [10] => d [11] => u [12] => l [13] => k [14] => a [15] => r )
?>

14) Find the 2nd last salary. What will happen when two salaries are same in MySql?

  SELECT * FROM employee ORDER BY salary DESC LIMIT 1, 1
But the above query will be fail same salary occurs multiple times in table.
1
2
3
4
5
6
7
8
+----+---------+--------+
| id | name    | salary |
+----+---------+--------+
|  1 | Sachin  |  20000 |
|  2 | William |  25000 |
|  3 | Tom     |  20000 |
|  4 | Anky    |  25000 |
+----+---------+--------+

So below is the right query:
SELECT * FROM employee GROUP BY salary ORDER BY salary DESC LIMIT 1, 1

15) Write a query to find all students who have taken admission in before 1 month from “students” table.

1
SELECT * FROM `students` WHERE admission_date <= date_sub(curdate(), INTERVAL 1 month);

16) Write a query to find all coming payments from “payments” table.

1
SELECT * FROM `payments` WHERE payment_date >= curdate(); 

17) Write a query to find all customers who have purchasing amount in greater than 1000.

1
2
3
4
5
6
7
8
9
+----+---------------+--------------+
| id | customer_name | purchase_amt |
+----+---------------+--------------+
|  1 | Sachin        |          500 |
|  2 | William       |          800 |
|  3 | William       |          400 |
|  4 | William       |          700 |
|  5 | Sachin        |          100 |
+----+---------------+--------------+

SELECT customer_name, SUM(purchase_amt) FROM customers_orders GROUP BY customer_name HAVING SUM(purchase_amt) > 1000;

18) Write a select query for below table so that F should display as FEMALE and M should display as MALE for gender field.

1
2
3
4
5
6
7
8
9
+----+---------------+--------------+--------+
| id | customer_name | purchase_amt | gender |
+----+---------------+--------------+--------+
|  1 | Soha          |          500 | F      |
|  2 | William       |          800 | M      |
|  3 | Honey         |          400 | F      |
|  4 | Tom           |          700 | M      |
|  5 | Sachin        |          100 | M      |
+----+---------------+--------------+--------+

SELECT customer_name, purchase_amt, (CASE WHEN gender = ‘F’ THEN ‘FEMALE’ WHEN gender = ‘M’ THEN ‘MALE’ END) AS gender FROM customers_orders;

19) Write a select query to implement SELF JOIN.

1
2
3
4
5
6
7
8
9
10
+----+------------+---------+
| id | reports_to | name    |
+----+------------+---------+
|  1 |          0 | Sachin  |
|  2 |          0 | William |
|  3 |          2 | Tom     |
|  4 |          1 | Anky    |
|  5 |          1 | Mona    |
|  6 |          3 | Vincy   |
+----+------------+---------+
1
2
3
4
5
6
7
8
SELECT
    e1.name AS 'Manager',
    e2.name AS 'Report To'
FROM
    employee e1
        INNER JOIN
    employee e2 ON e2.id = e1.reports_to
ORDER BY e1.id DESC

20) Write a program to display the below the pattern.

1
2
3
4
5
*
* *
* * *
* * * *
* * * * *
1
2
3
4
5
6
7
8
<?php
for($i = 1;$i<=5;$i++){
    for($j=1;$j<=$i;$j++){
        echo "*";
    }
    echo "<br>";
}
?>

21) Write a program to display the below the pattern.

1
2
3
4
5
* * * * *
* * * *
* * *
* *
*
1
2
3
4
5
6
7
8
<?php
for($i = 5;$i>=1;$i--){
    for($j=0;$j<$i;$j++){
        echo "*";
    }
    echo "<br>";
}
?>

22) Write a program to display the below pattern.

1
2
3
4
5
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
1
2
3
4
5
6
7
8
<?php
for($i = 1;$i<=5;$i++){
    for($j=1;$j<=$i;$j++){
        echo $i;
    }
    echo "<br>";
}
?>

23) Write a program to display the below the pattern.

1
2
3
4
1
2 3
4 5 6
7 8 9 10
1
2
3
4
5
6
7
8
9
10
<?php
$k = 1;
for($i = 1; $i<=4; $i++){
    for($j=1; $j<=$i; $j++){
        echo $k;
        $k++;
    }
    echo "<br>";
}
?>

24) Write a program to display the below pattern.

1
2
3
4
      1
    1 2 1
  1 2 3 2 1
1 2 3 4 3 2 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
for($i = 1; $i<=4; $i++){
    for($j=4; $j>=$i; $j--){
        echo "  ";
    }
    for($k=1; $k<=$i; $k++){
        echo $k;
    }
    for($m=($i-1); $m>=1; $m--){
        echo $m;
    }
    echo "<br>";
}
?>

25) Write a program to display the below pattern.

1
2
3
4
   *
  ***
 *****
*******
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
for($i = 1; $i<=4; $i++){
    for($j=4; $j>=($i + 1); $j--){
        echo "  ";
    }
    for($k=1; $k<=$i; $k++){
        echo "*";
    }
    for($m=2; $m<=$i; $m++){
        echo "*";
    }
    echo "<br>";
}
?>

26). How to find whether a year leap year or not?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
    if(isset($_POST['submit']))
    {
    $year=$_POST['year'];
    if($year%4==0)
    {
    echo "It is a leap year";
    }
    else
     {
       echo "It is not a leap year";
     }
}
 ?>
 <!DOCTYPE html>
 <html>
 <head>
 <title>How to check Leap year In PHP form</title>
 </head>
 <body>
 <form name="leapyear" action="" method="post">
 Year :<input type="text" name="year" value="" required=""><br /><br />
 <input type="submit" value="Submit" name="submit">
 </form>
 </body>
 </html>

27) How to Swap two variables without using the third variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
if(isset($_POST['submit']))
{
$value1=$_POST['num1'];
$value2=$_POST['num2'];
$value1=$value1+$value2;
$value2=$value1-$value2;
$value1=$value1-$value2;
        echo "Value of first variable after swapping" .$value1."<br />";
        echo "Value of second variable after swapping"  .$value2;
}
?>
<!DOCTYPE html>
 <html>
 <head>
 <title>How to Swap two variable without using third variable</title>
 </head>
 <body>
 <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
 Number 1 :<input type="text" name="num1" value="" required=""><br /><br />
 Number 2 :<input type="text" name="num2" value="" required=""><br />
 <input type="submit" value="Submit" name="submit">
 </form>
 </body>
 </html>

28) How to find whether a number prime or not?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
if(isset($_POST['submit'])) {
    $check=0;
    $num=$_POST['num'];
    for($i=2;$i<=($num/2);$i++) {
      if($num%$i==0) {
        $check++;
        if($check==1) {
         break ;
        }
      }
    }
    if($check==0) {
     echo "It is a Prime Number";
    }
    else {
     echo "It is not a Prime Number";
    }
}
?>
<!DOCTYPE html>
 <html>
 <head>
 <title>Check whether a number prime or not</title>
 </head>
 <body>
 <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
 Number :<input type="text" name="num" value="" required><br>
 <input type="submit" value="Submit" name="submit">
 </form>
 </body>
 </html>