Sie sind auf Seite 1von 125

Top Answers to MongoDB Interview Questions

1) Explain what is MongoDB?

Mongo-DB is a document database which provides high performance, high


availability and easy scalability.

2) What is “Namespace” in MongoDB?

MongoDB stores BSON (Binary Interchange and Structure Object Notation)


objects in the collection. The concatenation of the collection name and database
name is called a namespace.

3) What is sharding in MongoDB?

The procedure of storing data records across multiple machines is referred as


Sharding. It is a MongoDB approach to meet the demands of data growth. It is
the horizontal partition of data in a database or search engine. Each partition is
referred as shard or database shard.

4) How can you see the connection used by Mongos?

To see the connection used by Mongos use db_adminCommand


(“connPoolStats”);

5) Explain what is a replica set?

A replica set is a group of mongo instances that host the same data set. In
replica set, one node is primary, and another is secondary. From primary to the
secondary node all data replicates.

6) How replication works in MongoDB?

Across multiple servers, the process of synchronizing data is known as


replication. It provides redundancy and increase data availability with multiple
copies of data on different database server. Replication helps in protecting the
database from the loss of a single server.

7) While creating Schema in MongoDB what are the points need to be taken
in consideration?

Points need to be taken in consideration are


 Design your schema according to user requirements
 Combine objects into one document if you use them together. Otherwise,
separate them
 Do joins while write, and not when it is on read
 For most frequent use cases optimize your schema
 Do complex aggregation in the schema

8) What is the syntax to create a collection and to drop a collection in


MongoDB?

 Syntax to create collection in MongoDB is


db.createCollection(name,options)
 Syntax to drop collection in MongoDB is db.collection.drop()

9) Explain what is the role of profiler in MongoDB?

MongoDB database profiler shows performance characteristics of each operation


against the database. You can find queries using the profiler that are slower than
they should be.

10) Explain can you move old files in the moveChunk directory?

Yes, it is possible to move old files in the moveChunk directory, during normal
shard balancing operations these files are made as backups and can be deleted
once the operations are done.

11) To do safe backups what is the feature in MongoDB that you can use?

Journaling is the feature in MongoDB that you can use to do safe backups.

12) Mention what is Objecld composed of?

Objectld is composed of

 Timestamp
 Client machine ID
 Client process ID
 3 byte incremented counter

13) Mention what is the command syntax for inserting a document?

For inserting a document command syntax is database.collection.insert


(document).
14) Mention how you can inspect the source code of a function?

To inspect a source code of a function, without any parentheses, the function


must be invoked.

15) What is the command syntax that tells you whether you are on the
master server or not? And how many master does MongoDB allow?

Command syntax Db.isMaster() will tell you whether you are on the master
server or not. MongoDB allows only one master server, while couchDB allows
multiple masters.

16) Mention the command syntax that is used to view Mongo is using the
link?

The command syntax that is used to view mongo is using the link is
db._adminCommand(“connPoolStats.”)

17) Explain what are indexes in MongoDB?

Indexes are special structures in MongoDB, which stores a small portion of the
data set in an easy to traverse form. Ordered by the value of the field specified in
the index, the index stores the value of a specific field or set of fields.

18) Mention what is the basic syntax to use index in MongoDB?

The basic syntax to use in MongoDB is >db.COLLECTION_NAME.ensureIndex (


{KEY:1} ). In here the key is the the name of the COLUMN (or KEY:VALUE pair) which
is present in the documents.

19) Explain what is GridFS in MongoDB?

For storing and retrieving large files such as images, video files and audio files
GridFS is used. By default, it uses two files fs.files and fs.chunks to store the
file’s metadata and the chunks.

20) What are alternatives to MongoDB?

Cassandra, CouchDB, Redis, Riak, Hbase are a few good alternatives.

2. What makes MongoDB the best?


MongoDB is considered to be best NoSQL database because of :Document-oriented (DO)
High performance (HP)
High availability (HA)
Easy scalability
Rich query language

3. How to do transactions/locking in MongoDB?


MongoDB does not use conventional locking with reduction, as it is planned to be light, high-
speed and knowable in its presentation. It can be considered as parallel to the MySQL MyISAM
auto entrust sculpt. With simplest business sustain, performance is enhanced, particularly in a
structure with numerous servers.

4. When and to what extent does Data get extended to Multi-slice?


The MongoDB scrap stands on a collection. So an album of all substances is kept in a lump or
mass. Only when there is an additional time slot, there will be more than a few slice data
achievement choices, but when there is more than 1 lump, data gets extended to a lot of slices
and it can be extended to 64 MB.

5. Judge against MongoDB with Couchbase and CouchbaseDB?


Although Mongo DB with Couchbase and Couchbase DB are common in many ways, but still
they are different in the case of necessities for execution of the model, crossing points, storage,
duplications, etc.

6. When do we use Namespace in MongoDB?


During sequencing of the names of the database and collection name Namespace is used.

7. If you remove an object attribute, is it deleted from the database?


Yes, it is deleted. So better eliminate the attribute and then save the object again.

8. How can we move the old file in the moveChunk directory?


Once the functions are done, the old files are converted to backup files and moved to the
moveChunk directory at the time of balancing the slices.

9. Explain the situation when an index does not fit into RAM?
When an index is too huge to fit into RAM, then MongoDB reads the index, which is faster than
reading RAM because the indexes easily fit into RAM if the server has got RAM for indexes
along with the remaining set.

10. How does MongoDB provide consistency?


MongoDB uses the reader-writer locks, allowing simultaneous readers to access any supply like
a database or any collection. But always offers private access to singles writes.
11. Why is MongoDB not chosen for a 32-bit system?
Mongo DB is not considered as a 32-bit system because for running the 32-bit MongoDB, with
the server, information and indexes require 2 GB. So only it is not used in 32-bit devices.

12. How does Journaling work in MongoDB?


Write operations are saved in the memory while journaling is going on. The on-disk journal files
are really dependable for the reason that the journal writes are habitual. Inside dbPath, a journal
subdirectory is designed by MongoDB.

13. How can you isolate our cursors from intervening with the write operations?
Snapshot () method is used to isolate cursors from intervening with writes. This method
negotiates the index and makes sure that each query comes to any article only once.

14. Define MongoDB.


It is document oriented database which is used to high availability, easy scalability and high
performance. It supports the dynamic schema design.

15. Explain replica set.


It is a group of mongo instances that maintain same data set. Replica sets provide redundancy
and high availability, and are the basis for all production deployments.

16. What are the key features of mongodb?


There are 3 main features of mongodb that are automatic scaling, High performance and high
availability.

17. What is CRUD?


Mongodb provides CRUD operations that are create, Read, Update, Delete.
To learn more about MongoDB CRUD operations click here.

18. What is sharding?


Sharding means to store the data on the multiple machines.

19. What is Aggregation in MongoDB?


Aggregations are operations that process data records and return computed results.

20. Define the namespace in mongodb?


It is the concatenation of collection name and database.

21. Which syntax is used to create collection in mongodb?


db.createCollection(name,options) is used to create collection in mongodb.
22. Which syntax is used to drop collection in mongodb?
db.collection.drop() is used to drop collection in mongodb.

23. Explain Replication.


Replication is the process of synchronizing data across multiple servers.

24. What is the use of Index in mongodb?


Indexes provide high performance read operations for frequently used queries.

25. Which command is used for inserting a document?


database.collection.insert (document) is used for inserting a document.

26. What is use of GridFS in mongodb?


GridFS is used for storing and retrieving the large files like audio, Images, Video files.

27. What is the use journaling?


Journaling is used to safe backups in mongodb.

28. Which command is used to see the connection?


db_adminCommand (“connPoolStats”); is used to see the connection.

29. Define primary replica sets?


The primary replica set accepts all write operations from clients.

30. Define secondary replica sets.


The secondaries (page 565) replicate the primary’s oplog and apply the operations to their data
sets such that the secondaries’ data sets reflect the primary’s data set.

31. What is the use of profiler?


Profiler is used to show the performance characteristics of every operation against the database.

32. Which type of data mongodb store?


MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

33. What is purpose of replication?


Replication provides redundancy and increases data availability.

34. what is embedded documents?


Embedded documents capture relationships between data by storing related data in a single
document structure.
35. Define application level encryption.
Application Level Encryption provides encryption on a per-field or per-document basis within
the application layer.

36. What is storage encryption?


Storage Encryption encrypts all MongoDB data on the storage or operating system to ensure that
only authorized processes can access protected data.

37. Which method is used to create an index?


CreateIndex() method is used to create an index.

38. What is replica set oplog?


The oplog records all operations that modify the data in the replica set.

39. What is vertical scaling?


Vertical scaling adds more CPU and storage resources to increase capacity.

40. Define horizontal scaling.


It divides the data set and distributes the data over multiple servers, or shards.

41. What are the components of shared cluster?


Sharded cluster has the following components: shards, query routers and config servers.

42. Which command is use to create database?


DATABASE_NAME command is used to create database.

43. Which command is use to drop database?


db.dropDatabse() command is used to drop the database.
44. What is the use of pretty() method?
Pretty() method is used to show the results in a formatted way.

45. Which method is used to remove the document form the collection?
Remove() method is used to remove the document form the collection.

46. Define Mongodb projection.


Projection is used to select only necessary data.It did not select whole data of a document.

47. What is the use of limit() method?


Limit() method is used to limit the records in database.
48. What is the syntax of limit() method?
>db.COLLECTION_NAME.find().limit(NUMBER) syntax is used.

49. What is the syntax of sort() method?


>db.COLLECTION_NAME.find().sort({KEY:1}) syntax is used for sorting the documents.

50. Which command is used to create the backup of database?


Mongodump command is used to create the backup of database.

51. What is collection in monodb?


In monogodb collection is a group of mongodb documents.

52. What is the use of db command?


Db command gives the name of currently selected database.

53. Which method is used to update the documents into a collection?


Update() and save() methods are used to update the documents into a collection.

54. What is the syntax of skip() method?


The syntax of skip methopd is
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER).

55. Which command is used to restore the backup?


Mongorestore command is used to restore the backup.

56. What is the use of Dot notation in mogodb?


MongoDB uses the dot notation to access the elements of an array and to access the fields of an
embedded document.
57. Define auditing.
Auditing provides administrators with the ability to verify that the implemented security policies
are controlling activity in the system.

58. Define Aggregation Pipeline.


It is a framework for performing aggregation tasks.T he pipeline is used to transform the
documents into aggregated results.

59. Define Map reduce.


Map-reduce is a generic multi-phase data aggregation modality which is used for processing
quantities of data.
60. What is splitting in mongodb?
It is a background process that is used to keep chunks from growing too large.

61. Which language is used to wite mongodb?


C++ language is used for writing and implementing mongodb.

62. In which format mongodb stores the data?


Mongodb uses collection to store the data rather than in table.

63. What is the use of save() method?


Save() method is used to replace the existing document to the new document.

64. What is MongoDB?


MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a
NoSQL database, MongoDB eschews the traditional table-based relational database structure in
favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON),
making the integration of data in certain types of applications easier and faster. Released under a
combination of the GNU Affero General Public License and the Apache License, MongoDB is
free and open-source software.
First developed by the software company 10gen (now MongoDB Inc.) in October 2007 as a
component of a planned platform as a service product, the company shifted to an open source
development model in 2009, with 10gen offering commercial support and other services. Since
then, MongoDB has been adopted as backend software by a number of major websites and
services, including Craigslist, eBay, Foursquare, SourceForge, Viacom, and the New York
Times, among others. MongoDB is the most popular NoSQL database system.

65. What is the use of MongoDB?


MongoDB is relational database management system (RDBMS) replacement for web
applications. So when you have something which is close to RDBMS, MongoDB could be of
good use. It gives you that additional partition tolerance which RDMBS doesn’t give but it has
problems with availability. But if you want more scalability, MongoDB would be your choice.
It’s suitable for real-time analytics and high speed logging. It’s highly scalable as well. Craigslist
uses MongoDB for archived posts.
66. What do you understand by NoSQL databases? Is MongoDB a NoSQL database?
Explain.
At the present time, the internet is loaded with big data, big users, big complexity etc. and also
becoming more complex day by day. NoSQL is answer of all these problems; it is not a
traditional database management system, not even a relational database management system
(RDBMS). NoSQL stands for “Not Only SQL”. NoSQL is a type of database that can handle and
sort all type of unstructured, messy and complicated data. It is just a new way to think about the
database.Yes. MongoDB is a NoSQL database.
67. What type of DBMS is MongoDB?
MongoDB is a document oriented DBMS>

68. What is the difference between MongoDB and MySQL?


Although MongoDB and MySQL both are free and open source databases, there is a lot of
difference between them in the term of data representation, relationship, transaction, querying
data, schema design and definition, performance speed, normalization and many more. To
compare MySQL with MongoDB is like a comparison between Relational and Non-relational
databases.

69. What is the use of MongoDB?

 MongoDB is typically used as the primary data store for operational applications with
real-time requirements (i.e., low-latency, high availability). MongoDB is generally a
good fit for 60%-80% of the applications you may be building today. MongoDB is easy
to operate and scale in ways that are hard if not impossible with relational databases.
 MongoDB excels in many use cases where relational databases aren’t a good fit, like
applications with unstructured, semi-structured and polymorphic data, as well as
applications with large scalability requirements or multi-data center deployments.
 MongoDB may not be a good fit for some applications. For example, applications that
require complex transactions (e.g., a double-entry bookkeeping system) and scan-
oriented applications that access large subsets of the data most of the time may not be a
good fit for MongoDB. MongoDB is not a drop-in replacement for legacy applications
built around the relational data model and SQL.
 Some common use cases include mobile apps, product catalogs, real-time
personalization, content management and applications delivering a single view across
multiple systems

70. What kind of database is MongoDB?


MongoDB is a document-oriented DBMS. Think of MySQL but with JSON-like objects
comprising the data model, rather than RDBMS tables. Significantly, MongoDB supports neither
joins nor transactions. However, it features secondary indexes, an expressive query language,
atomic writes on a per-document level, and fully-consistent reads.
Operationally, MongoDB features master-slave replication with automated failover and built-in
horizontal scaling via automated range-based partitioning.

71. What language is MongoDB written in?


MongoDB is implemented in C++. Drivers and client libraries are typically written in their
respective languages, although some drivers use C extensions for better performance.

72. What are the limitations of 32-bit versions of MongoDB?


MongoDB uses memory-mapped files. When running a 32-bit build of MongoDB, the total
storage size for the server, including data and indexes, is 2 gigabytes. For this reason, do not
deploy MongoDB to production on 32-bit machines.
If you’re running a 64-bit build of MongoDB, there’s virtually no limit to storage size. For
production deployments, 64-bit builds and operating systems are strongly recommended.
73. While creating Schema in MongoDB what are the points need to be taken in
consideration?
Points need to be taken in consideration are:

 Design your schema according to user requirements


 Combine objects into one document if you use them together. Otherwise, separate them
 Do joins while write, and not when it is on read
 For most frequent use cases optimize your schema
 Do complex aggregation in the schemaThis blog will help you get a better understanding
of Difference Between Cassandra and MongoDB!

1) What is MongoDB?

MongoDB is a document database which provides good performance and it is a leading


NoSQL. It stores the document data in BSON structure.

2) In which language MongoDB is written?


MongoDB is written in C++.
3) What are the advantages of MongoDB?
Below are the advantages of MongoDB –

 Cross Platform
 Provides High Performance
 Easy scalability
 No Complex Joins
 Schema less
 Available on AWS, Azure etc.

4) What is a Database?

A Database is a container of all the Collections. Every database will have a physical file
associated in the file system.

5) What is a Collection?

The Collection is group of Documents in MongoDB. In RDBMS, this can be considered


as a table which will have list records (documents in MongoDB).

6) What is a Document?
The Document is a set of key-value pairs. In RDBMS, each record in a table is
equivalent to document in MongoDB. Documents will have a dynamic schema,
meaning, documents in a collection no need to have a same structure/fields.

7) Compare MongoDB and RDBMS?

Below are MongoDB equivalent in RDBMS –

MongoDB RDBMS

Database Database

Collection Table

Document Record/Row

Field Column

Embedded Documents Table Join

8) What is “mongod”?

It is a host process for the database. When we start mongod, it means starting the
MongoDB process and run it in the background.

9) What are the parameters for “mongod”?

Mongod Parameters are for following things -

 Storing the data in the given path. By default – “/data/db”.


 Port Number, By default – “27017”.

10) What is “mongo”?

It is the command shell used to connect to a specific instance of mongod. When we run
the mongo command with no parameters, it will try to connect to, default port number –
27017 and localhost.

11) What is the MongoDB command to switch the databases?


To switch the database in MongoDB use – “use databasename” command.

12) What is NoSQL?

NoSQL provides data retrieval and data storage. No SQL used in Big Data, Web Apps
etc. because of simple design and good performance.

13) What are the types of NoSQL?

Below are the types of NoSQL –

 Key-Value Store – It will have a has table with keys and values. (Eg : Amazon S3)
 Graph – It uses edge and nodes to represent the data. (Eg: Neo4J)
 Document Store – It stores data in the form of documents. (Eg: MongoDB)
 Column Based Store – Each Storage clock contains data from only one column. (Eg:
Cassandra)

14) Why to use MongoDB?

Below are the reasons to go for MongoDB –

 Data are stored in JSON which mean it’s supported in cross platform.
 Rich Queries
 Fast updates
 Support in MongoDB
 Replication and High Availability

15) Where we can use MongoDB?

Below are the places where we can use MongoDB –

 Big Data
 Content Management Systems
 Mobile Apps
 Data Management

16) What is the meaning of Namespace in MongoDB?

A Namespace is a combination of Database Name and Collection Name.

17) List out the Languages supported in MongoDB?

Below is the list of languages supported in MongoDB –

 C
 C++
 C#
 Java
 Node.JS
 Perl
 Php etc.

18) How to create a new database in MongoDB?


New database can be created using the command – “use database Name”, This
command will create a new database if there is no existing database or else it will return
the existing database.
19) What is the command used to check the list of databases in MongoDB?

To check the list of databases we need to use the command called – “show dbs”.

20) What is the meaning of Sharding in MongoDB?

Sharding is the process of keeping the data records in multiple machines. It is an


approach supported in MongoDB for data growth. It is like a horizontal partition and
each partition is called Shard.

21) How to see the connection used by MongoDB?

To see the connection used by MongoDB, use – “db_adminCommand


(“connPoolStats”);”.

22) What is Replication?

Replication is the process of synchronizing data across multiple servers. This will
increase the data availability as multiple of copies of data will be stored across multiple
servers.

23) What is replica set in MongoDB?

Replica set is the set of MongoDB instances carrying the same data set. In replica set,
one is the primary node, and another is secondary. Data replication is done from
primary to secondary node.

24) How to insert a document in the collection in MongoDB?

Below is the command to be used for inserting a document in MongoDB –

Db.CollectionName.Insert({“key”: “value” })
25) How to drop a database in MongoDB?

For dropping a database in MongoDB, use the following command –

Db.dropDatabase() – This will delete the selected database.

26) How to create a collection in MongoDB?

To create a collection of Customers in MongoDB, run the below command –

db.createCollection(“Customers”)

27) How we can check the Collections created in MongoDB?

Use the below command to check the Collections exists in the database –

Show collections

28) How we can drop a Collection in MongoDB?

Collection can be dropped using below command –

Db.CollectionName.drop()

29) Why to use Profiler in MongoDB?

MongoDB Profiler is used to check the performance characteristics of operations done


against the database.

30) Does MongoDB support Primary Key, Foreign Key relationships?

No. By default, MongoDB does not support Primary Key, Foreign Key relationships.

31) What are the different data types supported in MongoDB?

Below is the list of Data types supported in MongoDB –

 String
 Integer
 Double
 Boolean
 Object
 Object ID
 Arrays
 Min/Max Keys
 Datetime
 Code
 Regular Expression etc.

32) Why to use “Code” datatype in MongoDB?

“Code” datatype is used to store the Java script code in a document.

33) Why to use “Regular Expression” datatype in MongoDB?

“Regular Expression” datatype is used to store regular expression in a document.

34) Why to use “Object ID” datatype in MongoDB?

“Object ID” datatype is used to store document’s ID.


35) How to insert a Document in a Collection?
To insert a Document in Collection we can use below commands –

 Insert - db.CollectionName.Insert(document)
 Save - db.CollectionName.Save(document)

36) What is “ObjectID” is composed of?


ObjectID is composed of following things –

 Time Stamp
 Client Machine ID
 Client Process ID
 3 byte incremented counter

37) What are Indexes in MongoDB?

Indexes are used to execute the query efficiently. Without Indexes, MongoDB will
perform scan i.e, scanning all the documents in the collection.

38) How to give Indexes in MongoDB?

Indexes can be used like below –

db.COLLECTION_NAME.ensureIndex ( {ColumnName:1} )
ensureIndex() is used for creating an Index and “1” for ascending order, “-1” for
descending order.

39) What are the alternatives to MongoDB?

Below are the alternatives to MongoDB –

 Cassandra
 Redis
 Riak
 CouchDB

40) How to query documents in a Collection in MongoDB?

We can find a required Document in a Collection using command – “find()”

Db.CollectionName.find()

41) What is the method used to format the result in MongoDB?

"pretty()" method is used to format the results.

Db.CollectionName.find().pretty()

42) Give me an example of how we can apply “AND” or “OR” condition while
querying a document in a Collection?

We can use “AND” or “OR’’ queries like below –

db. CollectionName.find({$and:[{"Name":"AAA"},{"Address": "Test Addr"}]}).pretty()

db. CollectionName.find({$or:[{"Name":"AAA"},{"Address": "Test Addr"}]}).pretty()

43) How to update Documents in MongoDB?

For updating documents, we need to use below method –

db. CollectionName.update({filter criteria}, {$set: {new data}}, {mutli:true})


By default MongoDB update only one Document. To update multiple Documents we
need to specify - {mutli:true}.

44) How to delete Documents in MongoDB?

For deleting documents, we need to use below method –

db. CollectionName.remove({filter criteria})

45) Why to use the “Skip()” method in MongoDB?

“Skip()” method is used to skip number of Documents as given in the method.

Skip(3) - Skips 3 Documents.

46) How we can sort the Documents in MongoDB?

To sort the Documents we can use – “Sort()” method.

db. CollectionName.find({filter criteria }).sort({ColumnName:1})

Sort() method accepts the field on which the sorting has to be done and the sorting
order –

“1” – Ascending.

"-1" – Descending.

47) What is Aggregation in MongoDB?

Aggregation is used to process data and return the computed results. Aggregation can
perform a variety of operations on the grouped data and finally returns the single
result. It is like SQL Server Aggregators.

Top 85 JavaScript Interview Questions & Answers


1. What is JavaScript?
JavaScript is a client-side as well as server side scripting language that can be
inserted into HTML pages and is understood by web browsers. JavaScript is also
an Object based Programming language

2. Enumerate the differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded


program that can be introduced to HTML pages. These two languages are not at
all inter-dependent and are designed for the different intent. Java is an object -
oriented programming (OOPS) or structured programming language like C++ or
C whereas JavaScript is a client-side scripting language.

3. What are JavaScript Data Types?

Following are the JavaScript Data types:

 Number
 String
 Boolean
 Object
 Undefined

4. What is the use of isNaN function?

isNan function returns true if the argument is not a number otherwise it is false.

5. Between JavaScript and an ASP script, which is faster?

JavaScript is faster. JavaScript is a client-side language and thus it does not


need the assistance of the web server to execute. On the other hand, ASP is a
server-side language and hence is always slower than JavaScript. Javascript
now is also a server side language (nodejs).

6. What is negative infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing


negative number by zero.

7. Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, '\', at
the end of the first line

Example:
document.write("This is \a program");

And if you change to a new line when not within a string statement, then
javaScript ignores break in line.

Example:

var x=1, y=2,


z=
x+y;

The above code is perfectly fine, though not advisable as it hampers debugging.

8. Which company developed JavaScript?

Netscape is the software company who developed JavaScript.

9. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not
declared. If the program tries to read the value of an undeclared variable, then a
runtime error is encountered.

Undefined variables are those that are declared in the program but have not
been given any value. If the program tries to read the value of an undefined
variable, an undefined value is returned.

10. Write the code for adding new elements dynamically?

<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP);
}
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>

11. What are global variables? How are these variable declared and what
are the problems associated with using them?
Global variables are those that are available throughout the length of the code,
that is, these have no scope. The var keyword is used to declare a local variable
or object. If the var keyword is omitted, a global variable is declared.

Example:

// Declare a global globalVariable = "Test";

The problems that are faced by using global variables are the clash of variable
names of local and global scope. Also, it is difficult to debug and test the code
that relies on global variables.

12. What is a prompt box?

A prompt box is a box which allows the user to enter input by providing a text
box. Label and box will be provided to enter the text or number.

13. What is 'this' keyword in JavaScript?

'This' keyword refers to the object from where it was called.

14. Explain the working of timers in JavaScript? Also elucidate the


drawbacks of using the timer, if any?

Timers are used to execute a piece of code at a set time or also to repeat the
code in a given interval of time. This is done by using the functions setTimeout,
setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a


particular function after the mentioned delay. The setInterval(function,
delay) function is used to repeatedly execute the given function in the mentioned
delay and only halts when cancelled. The clearInterval(id)function instructs the
timer to stop.

Timers are operated within a single thread, and thus events might queue up,
waiting to be executed.

15. Which symbol is used for comments in Javascript?

// for Single line comments and

/* Multi

Line
Comment

*/

16. What is the difference between ViewState and SessionState?

'ViewState' is specific to a page in a session.

'SessionState' is specific to user specific data that can be accessed across all
pages in the web application.

17. What is === operator?

=== is called as strict equality operator which returns true when the two operands
are having the same value without any type conversion.

18. Explain how can you submit a form using JavaScript?

To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();

19. Does JavaScript support automatic type conversion?

Yes JavaScript does support automatic type conversion, it is the common way of
type conversion used by JavaScript developers

20. How can the style/class of an element be changed?

It can be done in the following way:

document.getElementById("myText").style.fontSize = "20?;

or

document.getElementById("myText").className = "anyclass";

21. Explain how to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

 Using JavaScript extensions


 Using a web page and Active X objects
22. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

 For
 While
 do-while loops

23. What is called Variable typing in Javascript?

Variable typing is used to assign a number to a variable and the same variable
can be assigned to a string.

Example

i = 10;
i = "string";

This is called variable typing.

24. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases.


parseInt() takes the string to be converted as its first parameter, and the second
parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be -

parseInt ("4F", 16);

25. Explain the difference between "==" and "==="?

"==" checks only for equality in value whereas "===" is a stricter equality test and
returns false if either the value or the type of the two variables are different.

26. What would be the result of 3+2+"7"?

Since 3 and 2 are integers, they will be added numerically. And since 7 is a
string, its concatenation will be done. So the result would be 57.

27. Explain how to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the


navigator.platform string (property) should be used.
28. What do mean by NULL in Javascript?

The NULL value is used to represent no value or no object. It implies no object or


null string, no valid boolean value, no number and no array object.

29. What is the function of delete operator?

The delete keyword is used to delete the property as well as its value.

Example

var student= {age:20, batch:"ABC"};


delete student.age;

30. What is an undefined value in JavaScript?

Undefined value means the

 Variable used in the code doesn't exist


 Variable is not assigned to any value
 Property doesn't exist

31. What are all the types of Pop up boxes available in JavaScript?

 Alert
 Confirm and
 Prompt

32. What is the use of Void(0)?

Void(0) is used to prevent the page from refreshing and parameter "zero" is
passed while calling.

Void(0) is used to call another method without refreshing the page.

33. How can a page be forced to load another page in JavaScript?

The following code has to be inserted to achieve the desired effect:

<script language="JavaScript" type="text/javascript" >

<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

34. What is the data type of variables of in JavaScript?


All variables in the JavaScript are object data types.

35. What is the difference between an alert box and a confirmation box?

An alert box displays only one button which is the OK button.

But a Confirmation box displays two buttons namely OK and cancel.

36. What are escape characters?

Escape characters (Backslash) is used when working with special characters like
single quotes, double quotes, apostrophes and ampersands. Place backslash
before the characters to make it display.

Example:

document.write "I m a "good" boy"


document.write "I m a \"good\" boy"

37. What are JavaScript Cookies?

Cookies are the small test files stored in a computer and it gets created when the
user visits the websites to store information that they need. Example could be
User Name details and shopping cart information from the previous visits.

38. Explain what is pop()method in JavaScript?

The pop() method is similar as the shift() method but the difference is that the
Shift method works at the start of the array. Also the pop() method take the last
element off of the given array and returns it. The array on which is called is then
altered.

Example:

var cloths = ["Shirt", "Pant", "TShirt"];


cloths.pop();

//Now cloth becomes Shirt,Pant

39. Whether JavaScript has concept level scope?

No. JavaScript does not have concept level scope. The variable declared inside
the function has scope inside the function.
40. Mention what is the disadvantage of using innerHTML in JavaScript?

If you use innerHTML in JavaScript the disadvantage is

 Content is replaced everywhere


 We cannot use like "appending to innerHTML"
 Even if you use +=like "innerHTML = innerHTML + 'html'" still the old
content is replaced by html
 The entire innerHTML content is re-parsed and build into elements,
therefore its much slower
 The innerHTML does not provide validation and therefore we can
potentially insert valid and broken HTML in the document and break it

41. What is break and continue statements?

Break statement exits from the current loop.

Continue statement continues with next statement of the loop.

42. What are the two basic groups of dataypes in JavaScript?

They are as –

 Primitive
 Reference types.

Primitive types are number and Boolean data types. Reference types are more
complex types like strings and dates.

43. How generic objects can be created?

Generic objects can be created as:

var I = new object();

44. What is the use of type of operator?

'Typeof' is an operator which is used to return a string description of the type of a


variable.

45. Which keywords are used to handle exceptions?

Try… Catch---finally is used to handle exceptions in the JavaScript


Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}

46. Which keyword is used to print the text in the screen?

document.write("Welcome") is used to print the text – Welcome in the screen.

47. What is the use of blur function?

Blur function is used to remove the focus from the specified object.

48. What is variable typing?

Variable typing is used to assign a number to a variable and then assign string to
the same variable. Example is as follows:

i= 8;
i="john";

49. How to find operating system in the client machine using JavaScript?

The 'Navigator.appversion' is used to find the name of the operating system in


the client machine.

50. What are the different types of errors in JavaScript?

There are three types of errors:

 Load time errors: Errors which come up when loading a web page like
improper syntax errors are known as Load time errors and it generates the
errors dynamically.
 Run time errors: Errors that come due to misuse of the command inside
the HTML language.
 Logical Errors: These are the errors that occur due to the bad logic
performed on a function which is having different operation.

51. What is the use of Push method in JavaScript?


The push method is used to add or append one or more elements to the end of
an Array. Using this method, we can append multiple elements by passing
multiple arguments

52. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array.
This method is used to prepend one or more elements to the beginning of the
array.

53. What is the difference between JavaScript and Jscript?

Both are almost similar. JavaScript is developed by Netscape and Jscript was
developed by Microsoft .

54. How are object properties assigned?

Properties are assigned to objects in the following way -

obj["class"] = 12;

or

obj.class = 12;

55. What is the 'Strict' mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode,
JavaScript shows errors for a piece of codes, which did not show an error before,
but might be problematic and potentially unsafe. Strict mode also solves some
mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal "use strict" above the file.
This can be illustrated by the given example:

function myfunction() {
"use strict";
var v = "This is a strict mode function";
}

56. What is the way to get the status of a CheckBox?

The status can be acquired as follows -


alert(document.getElementById('checkbox1').checked);

If the CheckBox will be checked, this alert will return TRUE.

57. How can the OS of the client machine be detected?

The navigator.appVersion string can be used to detect the operating system on


the client machine.

58. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This
leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early
manipulation of the code.

59. How will you explain closures in JavaScript? When are they used?

Closure is a locally declared variable related to a function which stays in memory


when the function has returned.

For example:

function greet(message) {

console.log(message);

function greeter(name, age) {

return name + " says howdy!! He is " + age + " years old";

// Generate the message

var message = greeter("James", 23);

// Pass it explicitly to greet

greet(message);
This function can be better represented by using closures

function greeter(name, age) {

var message = name + " says howdy!! He is " + age + " years old";

return function greet() {

console.log(message);

};

// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();

60. How can a value be appended to an array?

A value can be appended to an array in the given manner -

arr[arr.length] = value;

61. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is -

for (variable name in object){


statement or block to execute
}

In each repetition, one property from the object is associated to the variable
name, and the loop is continued till all the properties of the object are depleted.

62. Describe the properties of an anonymous function in JavaScript?


A function that is declared without any named identifier is known as an
anonymous function. In general, an anonymous function is inaccessible after its
declaration.

Anonymous function declaration -

var anon = function() {


alert('I am anonymous');
};
anon();

63. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little
difference. .call() is used when the number of the function's arguments are known
to the programmer, as they have to be mentioned as arguments in the call
statement. On the other hand, .apply() is used when the number is not known.
The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are
passed to the function. Their usage can be illustrated by the given example.

var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

alert(prefix + this.myProperty + postfix);


}
};
someObject.myMethod('<', '>'); // alerts '<Foo>'
var someOtherObject = {

myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'

someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'

64. Define event bubbling?


JavaScript allows DOM elements to be nested inside each other. In such a case,
if the handler of the child is clicked, the handler of parent will also work as if it
were clicked too.

65. Is JavaScript case sensitive? Give an example?

Yes, JavaScript is case sensitive. For example, a function parseInt is not same
as the function Parseint.

66. What boolean operators can be used in JavaScript?

The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be used
in JavaScript.

*Operators are without the parenthesis.

67. How can a particular frame be targeted, from a hyperlink, in JavaScript?

This can be done by including the name of the required frame in the hyperlink
using the 'target' attribute.

<a href="/newpage.htm" target="newframe">>New Page</a>

68. What is the role of break and continue statements?

Break statement is used to come out of the current loop while the continue
statement continues the current loop with a new recurrence.

69. Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is
that web-garden is a setup that includes many processors in a single server while
web-farm is a larger setup that uses more than one server.

70. How are object properties assigned?

Assigning properties to objects is done in the same way as a value is assigned to


a variable. For example, a form object's action value is assigned as 'submit' in
the following manner - Document.form.action="submit"

71. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor),
example for opening of a file -
fh = fopen(getScriptPath(), 0);

72. How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various
objects in a document interact with each other. DOM is required for developing
web pages, which includes objects like paragraph, links, etc. These objects can
be operated to include actions like add or delete. DOM is also required to add
extra capabilities to a web page. On top of that, the use of API gives an
advantage over other existing models.

73. How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a
form, by the user. An event handler is required to manage proper execution of all
these events. Event handlers are an extra attribute of the object. This attribute
includes event's name and the action taken if the event takes place.

74. Explain the role of deferred scripts in JavaScript?

By default, the parsing of the HTML code, during page loading, is paused until
the script has not stopped executing. It means, if the server is slow or the script is
particularly heavy, then the webpage is displayed with a delay. While using
Deferred, scripts delays execution of the script till the time HTML parser is
running. This reduces the loading time of web pages and they get displayed
faster.

75. What are the various functional components in JavaScript?

The different functional components in JavaScript are-

First-class functions: Functions in JavaScript are utilized as first class objects.


This usually means that these functions can be passed as arguments to other
functions, returned as values from other functions, assigned to variables or can
also be stored in data structures.

Nested functions: The functions, which are defined inside other functions, are
called Nested functions. They are called 'everytime' the main function is invoked.

76. Write about the errors shown in JavaScript?

JavaScript gives a message if it encounters an error. The recognized errors are -


 Load-time errors: The errors shown at the time of the page loading are
counted under Load-time errors. These errors are encountered by the use
of improper syntax, and thus are detected while the page is getting loaded.
 Run-time errors: This is the error that comes up while the program is
running. It is caused by illegal operations, for example, division of a
number by zero, or trying to access a non-existent area of the memory.
 Logic errors: It is caused by the use of syntactically correct code, which
does not fulfill the required task. For example, an infinite loop.

77. What are Screen objects?

Screen objects are used to read the information from the client's screen. The
properties of screen objects are -

 AvailHeight: Gives the height of client's screen


 AvailWidth: Gives the width of client's screen.
 ColorDepth: Gives the bit depth of images on the client's screen
 Height: Gives the total height of the client's screen, including the taskbar
 Width: Gives the total width of the client's screen, including the taskbar

78. Explain the unshift() method ?

This method is functional at the starting of the array, unlike the push(). It adds the
desired number of elements to the top of an array. For example -

var name = [ "john" ];


name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);

The output is shown below:

[" joseph "," Jane ", " charlie ", " john "]

79. Define unescape() and escape() functions?

The escape () function is responsible for coding a string so as to make the


transfer of the information from one computer to the other, across a network.

For Example:

<script>
document.write(escape("Hello? How are you!"));
</script>
Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:

<script>
document.write(unescape("Hello%3F%20How%20are%20you%21"));
</script>

Output: Hello? How are you!

80. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is
used to convert the encoded URL back to normal.

<script>
var uri="my test.asp?name=ståle&car=saab";

document.write(encodeURI(uri)+ "<br>");

document.write(decodeURI(uri));
</script>

Output -

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab

81. Why it is not advised to use innerHTML in JavaScript?

innerHTML content is refreshed every time and thus is slower. There is no scope
for validation in innerHTML and, therefore, it is easier to insert rouge code in the
document and, thus, make the web page unstable.

82. What does the following statement declares?

var myArray = [[[]]];

It declares a three dimensional array.

83. How are JavaScript and ECMA Script related?


ECMA Script are like rules and guideline while Javascript is a scripting language
used for web development.

84. What is namespacing in JavaScript and how is it used?

Namespacing is used for grouping the desired functions, variables etc. under a
unique name. It is a name that has been attached to the desired functions,
objects and properties. This improves modularity in the coding and enables code
reuse.

85. How can JavaScript codes be hidden from old browsers that don't
support JavaScript?

For hiding JavaScript codes from old browsers:

Add "<!--" without the quotes in the code just after the <script> tag.

Add "//-->" without the quotes in the code just before the <script> tag.

Old browsers will now treat this JavaScript code as a long HTML comment.
While, a browser that supports JavaScript, will take the "<!--" and "//-->" as one-
line comments.

General Questions
1. How would you use persistent storage on browsers? What options would you use?
For HTML browsers, a good choice would be local storage and persistent storage. For non-HTML ones,
cookies are the best bet.

2. What is W3C?
W3C stands for World Wide Web Consortium which is the international standard for World Wide Web.
W3C is constantly busy trying to standardize the web and to make it accessible to all users. The company
was created in 1994.

3. What are two common ways in which you can reduce the load time of a web application?
There are quite a lot of ways you can reduce load time:
• Enable browser caching
• Optimize images
• Minify resources
• Minimize HTTP Requests
• Reduce redirects

4. What is graceful degradation?


Graceful degradation refers to the property that enables a system to function properly even in the event of
failure of either the system or a component of it.

5. What is DTD?
DTD stands for Document Type Declaration and it tells the browser which version of either HTML or
XHTML is being used.
6. What is the difference between "Web development" and "Web design".
Web development includes a lot of processes, and Web Design is part of it. Web design is used to
represent page layouts and graphical user interface. Web development is a wider term to mean planning,
coding, testing, debugging etc.

7. What is CORS? How does it work?


Cross-origin resource sharing (CORS) is a mechanism that allows many restricted resources (e.g. fonts,
js etc.) on a web page to be requested from another domain outside the domain from which the resource
originated. It’s a mechanism supported in HTML5 that manages XMLHttpRequest access to a domain
different.

8. Describe the key advantages of HTTP/2 as compared with HTTP 1.1.


HTTP/2 among other improvements, provides decreased latency to improve page load speed by
supporting:
• Server push technologies
• Prioritization of requests
• Data compression of HTTP headers
• An important operational benefit of HTTP/2 is that it avoids the head-of-line blocking problem in HTTP 1.
• Loading of page elements in parallel over a single TCP connection

9. How do you optimize a website’s assets?


There are several ways to do this, for example: file concatenation, file compression, CDN Hosting,
offloading assets, refining code etc.

10. What web browser do you use?


Because web developers should be familiar with all browsers in terms of testing their web projects the
best answer here is: All of them.

11. What’s the difference between standards mode and quirks mode?
Quirks mode is a default compatibility mode and may be different from browser to browser, which may
result to a lack of consistency in appearance from browser to browser.

12. Explain what is long polling?


Long polling is a web application development pattern used to emulate pushing data from the server to
the client. With long polling, the client requests information from the server in a similar way to a normal
poll. However, if the server does not have any information available for the client, instead of sending an
empty response, the server holds the request and waits for some information to be available.

HTML & HTML5 Questions

13. What is HTML?


HTML stands for HyperText Markup Language. It is the most popular markup language for creating
websites that can be viewed in a web browser.

14. What is the difference between HTML elements and tags?


HTML elements communicate to the browser how to render text. When surrounded by angular brackets
<> they form HTML tags, which come in pairs and surround text.

15. What does DOCTYPE mean?


The term DOCTYPE means Document Type Definition and tells the browser which type of HTML is used
on a webpage. Browsers use DOCTYPE to determine how to render a page. Failing to use DOCTYPE
will load your page in Quirks Mode.

16. What are the limitations when serving XHTML pages?


The main limitation is the poor browser support of XHTML. Internet Explorer and other user agents
cannot parse XHTML as XML. Thus, it is not that extensible language as one might think.

17. What is the syntax difference between a bulleted list and numbered list?
Bulleted lists use the <ul> tag, which stands for “unordered,” whereas <ol> is used to create an ordered
list.

18. What is the difference between a <div> and a <frame>?


A <div> is a container element for grouping and styling, whereas a <frame> creates divisions within a web
page and should be used within the <frameset> tag. The use of <frame> and <frameset> are no longer
popular and are now being replaced with the more flexible <iframe>, which has become popular for
embedding elements from other websites (ie. Youtube videos)
into a page.

19. What is the difference between the application model of HTML and HTML5?
There is not a big difference between the two. HTML5 is a continuum of HTML. There has been no major
paradigm shift. From a broader viewpoint, HTML was a simple language for laying out text and images on
a webpage, whereas HTML5 can be viewed as a development platform that does what HTML does that
and more, including better support for audio, video, and interactive graphics. It has a number of new
elements, supports offline data storage for applications, and has more robust exchange protocols.

20. What are some new HTML5 markup elements?


Among several: <article>, <aside>, <bdi>, <command>, <details>, <figure>, <figcaption>, <summary>,
<header>, <footer>, <hgroup>, <mark>, <meter>, <nav>, <progress>, <ruby>, <rt>, <section> and
<time>.

21. What are the new image elements in HTML5?


The new image elements in HTML5 are Canvas and WebGL. <canvas> is a new element that acts as a
container for graphical elements like images and graphics. WebGL stands forWeb Graphics Language, a
free cross-platform API that is used for creating 3D graphics in web browsers.

22. What are data- attributes good for?


data- attribute is used to assigns custom data to an element. The stored (custom) data can then be used
in the page’s JavaScript to create a more engaging user experience.

23. Describe the difference between cookies, sessionStorage, and localStorage.


Cookies are small text files that websites place in a browser for tracking or login purposes, and hold a
modest amount of data. Meanwhile, localStorage and sessionStorage are new objects, both of which are
storage specifications but vary in scope and duration. Local storage is more secure, and large amounts of
data can be stored locally, without affecting website performance. Futhermore, is it permanent.
sessionStorage only lasts as long as the duration of the longest open tab.

24. What are some of the major new API’s that come standard with HTML5?
Among others: Media API, Text Track API, Application Cache API, User Interaction, Data Transfer API,
Command API, and the History API.

25. What is the difference in caching between HTML5 and the old version of HTML?
An crucial new feature of HTML5 is the Application Cache which creates an offline version of a web
application. and stores website files such as HTML files, CSS, images, and JavaScript, locally. Obviously,
that speeds up site performance.

26. What is image map?


An image map is a list of coordinates relating to a specific image, created in order to hyperlink areas of
the image to different destinations (as opposed to a normal image link, in which the entire area of the
image links to a single destination).
27. What is the advantage of collapsing white space?
White spaces are blank sequences of space characters, which is actually treated as a single space
character in HTML. The browser collapses multiple space into a single space, so we can indent lines of
text without worrying about multiple spaces. This enables us to organize the code into a much more
readable format.

28. Do all HTML elements need both opening and closing tags?
Not really, elements like <img src=""/> or <input type=""/> don’t need a closing tag.

29. What is a marquee?


A marquee is used to enable scrolling text in a web page. To do this, just place whatever text you want to
appear scrolling within the <marquee> and </marquee> tags.

30. How do you create links to sections within the same page?
Links can be created using the <a> tag, with referencing through the use of the # symbol. For example,
we can have: <a href="#top">BACK TO TOP</a> which would result in the words “BACK TO TOP”
appearing on the webpage and links to a bookmark named top. We can then create a separate tag like:
<a name=top></a>
somewhere on the same webpage so that the user will be linked to that place when clicking on “BACK TO
TOP”.

31. What are the possible ways to apply CSS styles to a web page?
CSS can be applied in the following three ways:
• Linked: Create a separate .css file and add all the style for the web page there. Make sure the file is
linked to the HTML document(s) using the link tag
• Embedded: Inside the HTML document, open a style tag and inside that, add all styles just like you’d do
on a linked file.
• Inline: This is done by adding a style attribute inside an HTML element.
32. Explain the CSS box model.
CSS box model is made up of margins, borders, padding, and content. The box model provides a more
structured way to space elements in relationship to each other in web pages. In your browser’s developer
tools, the CSS box model is found at the end of the CSS section and it looks like this:
33. What is the difference between inline and block elements?
Basically, a block element will take up the whole width available, and comes with a line break before and
after. Examples of block level elements are: headings (i.e <h1>), paragraphs (<p>), divisions (<div>) etc.
In contrast, inline elements take up only the space they need, and do not force line breaks. Examples of
inline elements are: anchors (<a>), spans (<span>) etc.

34. What is grouping used for in CSS?


Grouping allows several elements of HTML to have the very same styles applied. It uses a single
declaration and selectors and separated by commas. For example:
h1, h2, .my-class {
font-weight: light;
}

35. What is a Class selector and how does it differ from an ID selector?
Class selectors are used to apply style to multiple HTML elements identified with the same class. Class
selectors are called within the CSS document by a ‘.’, followed by the class name, like this:
.class {
color: black;
}
The difference between classes and ID’s is that a HTML element can accept multiple classes, but only
one ID. That means ID’s are unique for HTML elements.

36. What is the difference between visibility:hidden and display:none?


Although these two properties seem similar, there is quite an important difference between the two:
• visibility:hidden hides the element, but it will still takes up space, this way affecting the layout of the
document.
• display:none also hides the element, but will not take up space and the page will appear as if the
element is not present.

37. What are CSS preprocessors and why do we use them?


CSS preprocessors convert code written in a preprocessed language like SASS or LESS into the same
old CSS we’ve been using for such a long time now. The main advantages of using preprocessors are:
• Ability to define variables
• Ability to use nested syntax
• Ability to create and use mixins (functions)
• Use of mathematical and operational functions
However, there are also some disadvantages like updating issues and debugging difficulties.

38. What are child selectors in CSS?


Child selectors represent a way of grouping (for styling) a set of elements that descend from a parent
element. Example:
section > span {
background-color: #eee;
}

39. What are grid systems and why do we use them in web pages?
Grid systems are structured rules that enable content to be stacked horizontally and vertically in a
consistent and sustainable way.
They find heavily usage in today’s websites because they offer increased producitvity while coding,
they’re versatile and ideal for responsive layouts.

40. How do we use shorthand properties and why?


Shorthand properties cannot be applied to any css property but only a few like: border, outline, padding,
background etc. Shorthand properties reduce file size thus improving page load time. The trick stands for
listing all property values on a single line, in a pre defined order that must be respected. An example
would be:
div {
background-color: #ccc;
background-image: url("img.png");
background-repeat: no-repeat;
background-position: right top;
}
This would be exactly the same as:
div {
background: #ccc url("img.png") no-repeat right top;
}

41. What is the purpose of the z-index and how is it used?


The z-index property specifies the stack order of an element within the document area (or a part of it). An
element with greater stack order will always be in front of an element with a lower stack order. However,
z-index only works on positioned elements
(position:absolute, position:relative, or position:fixed). It can have four kind of values:
Web Developer Interview Questions 10 / 18
• Auto: Sets the stack order equal to its parents.
• Number: Orders the stack order.
• Initial: Sets this property to its default value (0).
• Inherit: Inherits this property from its parent element.

42. List some of the new CSS propertied introduced with CSS3?
The following is a list of new properties added in CSS3:
• border-radius
• box-shadow
• text-shadow
• text-stroke
• background-size
• text-overflow
• resize
• transition
Also, other features like multiple backrounds which allows you to have two or more background in the
very same selector and flexible box model which ensures that elements behave predictably when the
page layout must accommodate different screen sizes and different display devices.

43. Explain what pseudo-classes are and their usage.


Pseudo clasess are used to define a special state of an element. Do note that pseudo classes are not
defined in the markup. They can be used for:
• Styling an element on mouse over (hover)
• Styling an element when it gets focus
• Styling visited/unvisited links

44. What is the CSS selector which allows you to target every element in a web page?
Called the universal selector and signed with an asterix (*), it sets all HTML element the same styling
rules as defined in the property declarations. For example:
*{
margin: 0;
padding: 10px;
}

45. What are media queries and how are they used?
A media query consists of a media type and at least one expression that limits the style sheets’ scope by
using media features, such as width, height, and color. Media queries, added in CSS3, let the
presentation of content be tailored to a specific range of output devices without having to change the
content itself. The usage of media queries is similar to this:
@media (max-width: 768px) {
.problem-class {
property: smaller;
}
}

46. Define event bubbling.


Because JavaScript allows DOM elements to be nested inside each other, if the handler of the child is
clicked, the handler of parent will also work as if it were clicked too. That sums up what event bubbling
really is.

47. How would you declare a three-dimensional array in Javascript?


You can do it like this:
var myArray = [[[]]];

48. What is "this" keyword in Javascript?


this is used to refer to the current object in the code. In the global execution context (outside of any
function), this refers to the global object, whether in strict mode or not.

49. Does Javascript support automatic type conversion?


Yes. JavaScript does support automatic type conversion and it is the common way of type conversion
used by JavaScript developers.

50. What is event delegation and how does it work?


Event delegation allows us to avoid adding event listeners to specific nodes of the DOM; instead, the
event listener is added to one parent. Using event delegation it’s possible to add an event handler to an
element, wait for an event to bubble up from a child element and easily determine from which element the
event originated.

51. What is the difference between window.onload and onDocumentReady?


The window.onload event will not trigger until every single element on the page has been fully loaded,
including CSS, images and/or other assets. The main disadvantage is that it might take a while before
any code is actually executed. On the other hand, onDocumentReady executes code as soon as DOM is
loaded.

52. Which is faster between Javascript and ASP?


Javascript is obviously faster. Why? Because Javascript is a client-side language and execution does not
need assistance from the web server. In contrast, ASP is server-side therefore is slower.

53. What is an anonymous function is Javascript


An anonymous function is a function declared without any named identifier and in general, is not
accessible after its declaration.

54. Explain the role of break and continue statements.


• Break statements are used to come out of the current loop
• Continue statements continue the current loop with a new recurrence

55. How are object properties assigned in JS?


Similar to the way a value is assigned to a variable, we assign object properties like this for example:
document.form.
action="submit"

56. What is the difference between undeclared and undefined variables?


• Undeclared variables are variables that do not exist in a program and are not declared. If the program
tries to read the value of an undeclared variable, then a runtime error is generated.
• Undefined variables are variables that are declared in the program but have not been given any value. If
the program tries to read the value of an undefined variable, an undefined value is returned.

57. What would be the result of 5+2+"3"?


Since 5 and 2 are integers (data type) they will be added together numerically. And since "3" is a string,
the result would be a concatination, meaning 73.

58. Name some Javascript functions used to convert non numerical values into numbers.
There are three main ways to do this:
• parseInt()
• parseFloat()
• Number()

59. What is namespacing in Javascript and how is it used?


Namespacing is used for grouping functions, variables etc. under a unique name. It is a name that has
been attached to the desired functions, objects and properties. This enables code reuse and improves
modularity in the coding.

60. What is a closure in Javascript?


A clouse resembles an object. It gets instatiated whenever you call a function. The scope of a closure is
lexical, meaning everything contained within the function in which the closure belongs to, has access to
any variable that is in it. A decent example would be:

function wcg() {
var name = "Web Code Geeks";
function displayMessage() {
alert(name);
}
displayMessage();
}
wcg();
wcg() creates a local variable name and then a function called displayMessage(). displayMessage() is an
inner function that is defined inside wcg() and is only available within the body of that
function.displayMessage() has no local variables of its own, however it has access to the variables of
outer functions and so can use the variable name declared in the parent function.

61. How is jQuery different to Javascript?


Well, jQuery is not a programming language, but a well written JavaScript code (a framework). It is a
library built with Javascript. Javascript is the core programming language. It is very popular because it
abstracts away cross-browser compatibility issues and emphasises unobtrusive and callback-driven
Javascript programming.

62. What is $() in jQuery?


The $() function is an alias of jQuery() function. $() function is used to wrap any object into jQuery object,
which then allows you to call various method defined in the jQuery object.

63. What are jQuery events?


Events are actions performed on specific conditions. When we perform these actions on an HTML page,
we can do whatever we want. We then use event handlers to perform the action. Some important
handlers are for example: bind(), unbind(),
blur(), off(), hover(), on(), one(), ready(),trigger() etc.

64. What is called chaining?


Chaining is used to connect multiple events and functions in a selector. It means specifying multiple
functions and/or selectors to an element.

65. What is the difference between event.PreventDefault and event.stopPropagation?


In short, preventDefault(): Stops the default action of an element from happening.
event.stopPropagation():
Prevents the event from bubbling up the DOM tree, thus preventing any parent handlers from being
notified of the event.

66. How can we hide an image on a button click using jQuery?


We can have a click handler and then the hide method applied to the image:
$("#button").click(function(){
$("#image").hide();
});

67. What is AJAX in jQuery?


AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server,
without reloading the whole page. It is a technique for creating fast and dynamic web pages.
• $.ajax() - Performs an async AJAX request.
• $.get() - Loads data from a server using an AJAX HTTP GET request.
• $.post() - Loads data from a server using an AJAX HTTP POST request.

68. What Is the Format of an AJAX Request?


An AJAX request can be in any of the following formats:
• Text File
• HTML
• JSON Object
69. How can you find out that an AJAX request has been completed?
We can use the ReadyState property to check whether AJAX request has been completed. If the property
is equal to 4, the request has been completed and data is now available.
70. Do AJAX requests retain PHP session info, when calling multiple times?
Yes, PHP retains the session info over multiple ajax calls. The duration of the php session depends on
SESSION configuration.

71. How can a file be included to a PHP page?


Two functions can be used to include a file: include() and require(). The file path shall be given as the
parameter in both
cases. For example
include("web-code-geeks.php");
require("admin_header.php");

72. What is the difference between echo and print in PHP?


Although almost everyone thinks both of these functions are the same, there are some slight differences
to consider:
• echo doesn’t return a value whereas print returns a value of 1
• print can only take a single argument, while echo can accept multiple parameters

73. What is a final class? What about a final method?


The final concept of classes and methods do also exist in other programming languages like Java, and in
PHP the explanation is similar:
• A final class means this class cannot be extended.
• A final method means it cannot be overrided.

74. How can we create a session in PHP? How do we set and unset values in sessions?
PHP provides the following to work with sessions:
• To create a session: session_start();
• To set a value into session: $_SESSION[’VAR’]=1;
• To remove data from a session: unset($_SESSION[’VAR’]);

75. How would you connect to MySQL database from a PHP script?
Using the mysql_connect() function we can connect to a MySQL database like so:
$database = mysql_connect("HOST", "USER_NAME", "PASSWORD"); mysql_select_db("DATABASE_NAME" -
,$database);

76. What are the main differences between GET, POST and REQUEST methods?
GET and POST are used to send information from client browser to web server. In case of GET the
information is send via GET method in name/value pair and is URL encoded. The default GET has a limit
of 512 characters. The POST method transfers the information via HTTP Headers. The POST method
does not have any restriction in data size to be sent. POST is used for sending data securely and ASCII
and binary type’s data. The $_REQUEST contains the content of both $_GET, $_POST and
$_COOKIE.

77. How can we find the length of a string in PHP? What about the length of an array?
PHP provides the strlen() function to find the length of a string and count() function for finding the array
length.

78. What is an associative array?


Associative arrays are arrays that use named keys that you assign to them. An example would be:
$langauges=array("Front-End"=>"Javascript", "Back-End"=>"PHP", "Framework"=>"AngularJS");

79. Can we send e-mail using PHP? How?


Yes, we can send e-mails in PHP using the mail() function. This function accepts 5 parameters from
which 2 are optional.
Example:
mail($to, $subject, $message, $headers);
80. How is a constant defined in PHP?
We can define a constant using the define() directive:
define("CONSTANT_NAME", 32);

81. What encryption techniques are there in PHP?


There are two encryption techniques widely used in PHP:
• MD5: The MD5 hash algorithm is implemented using the md5 function like so: $encrypted_string
=md5($string);
• mcrypt_encrypt: Encrypts plaintext with given parameters. The standard structure is: string
mcrypt_encrypt (string $cipher , string $key , string $data , string $mode [, string $iv ] )

82. Is it possible to extend the execution time of a PHP script?


Yes, that can be achieved using the set_time_limit(int seconds) which enables us to extend the execution
time of a php script. Note that the default limit is 30 seconds.

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


The header() function sends a raw HTTP header to a client browser. This function must be called before
sending the actual output.

84. How is the ternary conditional operator used in PHP?


The ternary conditional operator is used just like in most languages:
condition_here ? execute_if_true : execute_if_false;
Three expressions go into this kind of assignment, the condition and two operands describing what
should be executed when the condition is true or false.

85. How can we create a text file using PHP?


Most programming languages like C and Java let you create files. In PHP, the way we create files is:
$filename = "/directory/newfile.txt";
$file = fopen ($filename, "w"); // open with writing permissions

This is it. The file is created, and we’ve even granted access to write in it. Additionaly, we can check if the
file can be opened:
if ($file == false) {
echo ("File cannot be opened");
exit();
}
After writing or reading from file, we can close the file.
fwrite($file. "Writing on the file"); // in this case writing
fclose($file);

1) What is PHP?

PHP is a web language based on scripts that allow developers to dynamically


create generated web pages.

2) What do the initials of PHP stand for?

PHP means PHP: Hypertext Preprocessor.

3) Which programming language does PHP resemble?

PHP syntax resembles Perl and C


4) What does PEAR stand for?

PEAR means "PHP Extension and Application Repository". It extends PHP and
provides a higher level of programming for web developers.

5) What is the actually used PHP version?

Version 7.1 or 7.2 is the recommended version of PHP.

6) How do you execute a PHP script from the command line?

Just use the PHP command line interface (CLI) and specify the file name of the
script to be executed as follows:

php script.php

7) How to run the interactive PHP shell from the command line interface?

Just use the PHP CLI program with the option -a as follows:

php -a

8) What is the correct and the most two common way to start and finish a
PHP block of code?

The two most common ways to start and finish a PHP script are:

<?php [ --- PHP code---- ] ?> and <? [--- PHP code ---] ?>

9) How can we display the output directly to the browser?

To be able to display the output directly to the browser, we have to use the
special tags <?= and ?>.

10) What is the main difference between PHP 4 and PHP 5?

PHP 5 presents many additional OOP (Object Oriented Programming) features.

11) Is multiple inheritance supported in PHP?

PHP supports only single inheritance; it means that a class can be extended from
only one single class using the keyword 'extended'.

12) What is the meaning of a final class and a final method?


'final' is introduced in PHP5. Final class means that this class cannot be
extended and a final method cannot be overridden.

13) How is the comparison of objects done in PHP?

We use the operator '==' to test is two objects are instanced from the same class
and have same attributes and equal values. We can test if two objects are
referring to the same instance of the same class by the use of the identity
operator '==='.

14) How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass


pieces of information from HTML to PHP.

15) What type of operation is needed when passing values through a form
or an URL?

If we would like to pass values through a form or an URL, then we need to


encode and to decode them using htmlspecialchars() and urlencode().

16) How can PHP and Javascript interact?

PHP and Javascript cannot directly interact since PHP is a server side language
and Javascript is a client-side language. However, we can exchange variables
since PHP can generate Javascript code to be executed by the browser and it is
possible to pass specific variables back to PHP via the URL.

17) What is needed to be able to use image function?

GD library is needed to execute image functions.

18) What is the use of the function 'imagetypes()'?

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

19) What are the functions to be used to get the image's properties (size,
width, and height)?

The functions are getimagesize() for size, imagesx() for width and imagesy() for
height.
20) How failures in execution are handled with include() and require()
functions?

If the function require() cannot access the file then it ends with a fatal error.
However, the include() function gives a warning, and the PHP script continues to
execute.

21) What is the main difference between require() and require_once()?

require(), and require_once() perform the same task except that the second
function checks if the PHP script is already included or not before executing it.

(same for include_once() and include())

22) How can I display text with a PHP script?

Two methods are possible:

<!--?php echo "Method 1"; print "Method 2"; ?-->

23) How can we display information of a variable and readable by a human


with PHP?

To be able to display a human-readable result we use print_r().

24) How is it possible to set an infinite execution time for PHP script?

The set_time_limit(0) added at the beginning of a script sets to infinite the time of
execution to not have the PHP error 'maximum execution time exceeded.' It is
also possible to specify this in the php.ini file.

25) What does the PHP error 'Parse error in PHP - unexpected T_variable at
line x' means?

This is a PHP syntax error expressing that a mistake at the line x stops parsing
and executing the program.

26) What should we do to be able to export data into an Excel file?

The most common and used way is to get data into a format supported by Excel.
For example, it is possible to write a .csv file, to choose for example comma as a
separator between fields and then to open the file with Excel.

27) What is the function file_get_contents() useful for?


file_get_contents() lets reading a file and storing it in a string variable.

28) How can we connect to a MySQL database from a PHP script?

To be able to connect to a MySQL database, we must use mysqli_connect()


function as follows:

<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD"); mysqli_select_db($d


atabase,"DATABASE_NAME"); ?-->

29) What is the function mysql_pconnect() useful for?

mysql_pconnect() ensure a persistent connection to the database, it means that


the connection does not close when the PHP script ends.

This function is not supported in PHP 7.0 and above

30) How be the result set of Mysql handled in PHP?

The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc,


mysqli_fetch_object or mysqli_fetch_row.

31) How is it possible to know the number of rows returned in the result
set?

The function mysqli_num_rows() returns the number of rows in a result set.

32) Which function gives us the number of affected entries by a query?

mysqli_affected_rows() return the number of entries affected by an SQL query.

33) What is the difference between mysqli_fetch_object() and


mysqli_fetch_array()?

The mysqli_fetch_object() function collects the first single matching record where
mysqli_fetch_array() collects all matching records from the table in an array.

34) How can we access the data sent through the URL with the GET
method?

To access the data sent via the GET method, we use $_GET array like this:

www.url.com?var=value
$variable = $_GET["var"]; this will now contain 'value'
35) How can we access the data sent through the URL with the POST
method?

To access the data sent this way, you use the $_POST array.

Imagine you have a form field called 'var' on the form when the user clicks submit
to the post form, you can then access the value like this:

$_POST["var"];

36) How can we check the value of a given variable is a number?

It is possible to use the dedicated function, is_numeric() to check whether it is a


number or not.

37) How can we check the value of a given variable is alphanumeric?

It is possible to use the dedicated function, ctype_alnum to check whether it is an


alphanumeric value or not.

38) How do I check if a given variable is empty?

If we want to check whether a variable has a value or not, it is possible to use the
empty() function.

39) What does the unlink() function mean?

The unlink() function is dedicated for file system handling. It simply deletes the
file given as entry.

40) What does the unset() function mean?

The unset() function is dedicated for variable management. It will make a variable
undefined.

41) How do I escape data before storing it in the database?

The addslashes function enables us to escape data before storage into the
database.

42) How is it possible to remove escape characters from a string?

The stripslashes function enables us to remove the escape characters before


apostrophes in a string.
43) How can we automatically escape incoming data?

We have to enable the Magic quotes entry in the configuration file of PHP.

44) What does the function get_magic_quotes_gpc() means?

The function get_magic_quotes_gpc() tells us whether the magic quotes is


switched on or no.

45) Is it possible to remove the HTML tags from data?

The strip_tags() function enables us to clean a string from the HTML tags.

46) what is the static variable in function useful for?

A static variable is defined within a function only the first time, and its value can
be modified during function calls as follows:

<!--?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVar


iable++; } testFunction(); //1 testFunction(); //2 testFunction(); /
/3 ?-->

47) How can we define a variable accessible in functions of a PHP script?

This feature is possible using the global keyword.

48) How is it possible to return a value from a function?

A function returns a value using the instruction 'return $value;'.

49) What is the most convenient hashing method to be used to hash


passwords?

It is preferable to use crypt() which natively supports several hashing algorithms


or the function hash() which supports more variants than crypt() rather than using
the common hashing algorithms such as md5, sha1 or sha256 because they are
conceived to be fast. Hence, hashing passwords with these algorithms can
create vulnerability.

50) Which cryptographic extension provide generation and verification of


digital signatures?

The PHP-OpenSSL extension provides several cryptographic operations


including generation and verification of digital signatures.
51) How is a constant defined in a PHP script?

The define() directive lets us defining a constant as follows:

define ("ACONSTANT", 123);

52) How can you pass a variable by reference?

To be able to pass a variable by reference, we use an ampersand in front of it, as


follows $var1 = &$var2

53) Will a comparison of an integer 12 and a string "13" work in PHP?

"13" and 12 can be compared in PHP since it casts everything to the integer
type.

54) How is it possible to cast types in PHP?

The name of the output type has to be specified in parentheses before the
variable which is to be cast as follows:

* (int), (integer) - cast to integer

* (bool), (boolean) - cast to boolean

* (float), (double), (real) - cast to float

* (string) - cast to string

* (array) - cast to array

* (object) - cast to object

55) When is a conditional statement ended with endif?

When the original if was followed by: and then the code block without braces.

56) How is the ternary conditional operator used in PHP?

It is composed of three expressions: a condition, and two operands describing


what instruction should be performed when the specified condition is true or false
as follows:

Expression_1?Expression_2 : Expression_3;
57) What is the function func_num_args() used for?

The function func_num_args() is used to give the number of parameters passed


into a function.

58) If the variable $var1 is set to 10 and the $var2 is set to the character
var1, what's the value of $$var2?

$$var2 contains the value 10.

59) What does accessing a class via :: means?

:: is used to access static methods that do not require object initialization.

60) In PHP, objects are they passed by value or by reference?

In PHP, objects passed by value.

61) Are Parent constructors called implicitly inside a class constructor?

No, a parent constructor have to be called explicitly as follows:

parent::constructor($value)

62) What's the difference between __sleep and __wakeup?

__sleep returns the array of all the variables that need to be saved, while
__wakeup retrieves them.

63) What is faster?

1- Combining two variables as follows:

$variable1 = 'Hello ';

$variable2 = 'World';

$variable3 = $variable1.$variable2;

Or

2- $variable3 = "$variable1$variable2";
$variable3 will contain "Hello World". The first code is faster than the second
code especially for large large sets of data.

64) what is the definition of a session?

A session is a logical object enabling us to preserve temporary data across


multiple PHP pages.

65) How to initiate a session in PHP?

The use of the function session_start() lets us activating a session.

66) How can you propagate a session id?

You can propagate a session id via cookies or URL parameters.

67) 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.

68) When do sessions end?

Sessions automatically end when the PHP script finishes executing but can be
manually ended using the session_write_close().

69) What is the difference between session_unregister() and


session_unset()?

The session_unregister() function unregister a global variable from the current


session and the session_unset() function frees all session variables.

70) What does $GLOBALS mean?

$GLOBALS is associative array including references to all variables which are


currently defined in the global scope of the script.

71) What does $_SERVER mean?

$_SERVER is an array including information created by the web server such as


paths, headers, and script locations.

72) What does $_FILES means?


$_FILES is an associative array composed of items sent to the current script via
the HTTP POST method.

73) What is the difference between $_FILES['userfile']['name'] and


$_FILES['userfile']['tmp_name']?

$_FILES['userfile']['name'] represents the original name of the file on the client


machine,

$_FILES['userfile']['tmp_name'] represents the temporary filename of the file


stored on the server.

74) How can we get the error when there is a problem to upload a file?

$_FILES['userfile']['error'] contains the error code associated with the uploaded


file.

75) How can we change the maximum size of the files to be uploaded?

We can change the maximum size of files to be uploaded by changing


upload_max_filesize in php.ini.

76) What does $_ENV mean?

$_ENV is an associative array of variables sent to the current PHP script via the
environment method.

77) What does $_COOKIE mean?

$_COOKIE is an associative array of variables sent to the current PHP script


using the HTTP Cookies.

78) What does the scope of variables mean?

The scope of a variable is the context within which it is defined. For the most
part, all PHP variables only have a single scope. This single scope spans
included and required files as well.

79) what the difference between the 'BITWISE AND' operator and the
'LOGICAL AND' operator?

$a and $b: TRUE if both $a and $b are TRUE.

$a & $b: Bits that are set in both $a and $b are set.
80) What are the two main string operators?

The first is the concatenation operator ('.'), which returns the concatenation of its
right and left arguments. The second is ('.='), which appends the argument on the
right to the argument on the left.

81) What does the array operator '===' means?

$a === $b TRUE if $a and $b have the same key/value pairs in the same order
and of the same types.

82) What is the differences between $a != $b and $a !== $b?

!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity
(TRUE if $a is not identical to $b).

83) How can we determine whether a PHP variable is an instantiated object


of a certain class?

To be able to verify whether a PHP variable is an instantiated object of a certain


class we use instanceof.

84) What is the goto statement useful for?

The goto statement can be placed to enable jumping inside the PHP program.
The target is pointed by a label followed by a colon, and the instruction is
specified as a goto statement followed by the desired target label.

85) what is the difference between Exception::getMessage and Exception::


getLine?

Exception::getMessage lets us getting the Exception message and


Exception::getLine lets us getting the line in which the exception occurred.

86) What does the expression Exception::__toString means?

Exception::__toString gives the String representation of the exception.

87) How is it possible to parse a configuration file?

The function parse_ini_file() enables us to load in the ini file specified in filename
and returns the settings in it in an associative array.

88) How can we determine whether a variable is set?


The boolean function isset determines if a variable is set and is not NULL.

89) What is the difference between the functions strstr() and stristr()?

The string function strstr(string allString, string occ) returns part of allString from
the first occurrence of occ to the end of allString. This function is case-sensitive.
stristr() is identical to strstr() except that it is case insensitive.

90) what is the difference between for and foreach?

for is expressed as follows:

for (expr1; expr2; expr3)

statement

The first expression is executed once at the beginning. In each iteration, expr2 is
evaluated. If it is TRUE, the loop continues, and the statements inside for are
executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is
tested at the end of each iteration.

However, foreach provides an easy way to iterate over arrays, and it is only used
with arrays and objects.

91) Is it possible to submit a form with a dedicated button?

It is possible to use the document.form.submit() function to submit the form. For


example: <input type=button value="SUBMIT"
onClick="document.form.submit()">

92) What is the difference between ereg_replace() and eregi_replace()?

The function eregi_replace() is identical to the function ereg_replace() except that


it ignores case distinction when matching alphabetic characters.

93) Is it possible to protect special characters in a query string?

Yes, we use the urlencode() function to be able to protect special characters.

94) What are the three classes of errors that can occur in PHP?

The three basic classes of errors are notices (non-critical), warnings (serious
errors) and fatal errors (critical errors).
95) What is the difference between characters \034 and \x34?

\034 is octal 34 and \x34 is hex 34.

96) How can we pass the variable through the navigation between the
pages?

It is possible to pass the variables between the PHP pages using sessions,
cookies or hidden form fields.

97) Is it possible to extend the execution time of a PHP script?

The use of the set_time_limit(int seconds) enables us to extend the execution


time of a PHP script. The default limit is 30 seconds.

98) Is it possible to destroy a cookie?

Yes, it is possible by setting the cookie with a past expiration time.

99) What is the default session time in PHP?

The default session time in php is until the closing of the browser

100) Is it possible to use COM component in PHP?

Yes, it's possible to integrate (Distributed) Component Object Model components


((D)COM) in PHP scripts which is provided as a framework.

101) Explain whether it is possible to share a single instance of a


Memcache between multiple PHP projects?

Yes, it is possible to share a single instance of Memcache between multiple


projects. Memcache is a memory store space, and you can run memcache on
one or more servers. You can also configure your client to speak to a particular
set of instances. So, you can run two different Memcache processes on the
same host and yet they are completely independent. Unless, if you have
partitioned your data, then it becomes necessary to know from which instance to
get the data from or to put into.

102) Explain how you can update Memcached when you make changes to
PHP?

When PHP changes you can update Memcached by


 Clearing the Cache proactively: Clearing the cache when an insert or
update is made
 Resetting the Cache: It is similar to the first method but rather than just
deleting the keys and waiting for the next request for the data to refresh
the cache, reset the values after the insert or update.

Q #1) What is PHP?


Answer:
PHP is one of the popular server-side scripting languages for developing a web application.

The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for creating
dynamic content, communicating with a database server, handling session etc.

Q #2) Why do we use PHP?


Answer:
There are several benefits of using PHP. First of all, it is totally free to use. So anyone can use
PHP without any cost and host the site at a minimal cost.

It supports multiple databases. The most commonly used database is MySQL which is also free
to use. Many PHP frameworks are used now for web development, such as CodeIgniter,
CakePHP, Laravel etc.

These frameworks make the web development task much easier than before.

Q #3) Is PHP a strongly typed language?


Answer:
No. PHP is a weakly typed or loosely typed language.

Which means PHP does not require to declare data types of the variable when you declare any
variable like the other standard programming languages C# or Java. When you store any string
value in a variable then the data type is the string and if you store a numeric value in that same
variable then the data type is an Integer.

Sample code:
1 $var = "Hello"; //String
2 $var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer:
When the value of a variable is used as the name of the other variables then it is called variable
variables. $$ is used to declare variable variables in PHP.

Sample code:
1 $str = "PHP";
2 $$str = " Programming"; //declaring variable variables
3 echo "$str ${$str}"; //It will print "PHP programming"
4 echo "$PHP"; //It will print "Programming"
Q #5) What are the differences between echo and print?
Answer:
Both echo and print method print the output in the browser but there is a difference between
these two methods.
echo does not return any value after printing the output and it works faster than the print
method. print method is slower than the echo because it returns boolean value after printing the
output.
Sample code:
1 echo "PHP Developer";
2 $n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer:
You have to use PHP command in the command line to execute a PHP script. If the PHP file
name is test.php then the following command is used to run the script from the command line.
php test.php

Q #7) How can you declare the array in PHP?


Answer:
You can declare three types of arrays in PHP. They are numeric,
associative and multidimensionalarrays.
Sample code:
1 //Numeric Array
2 $computer = array("Dell", "Lenavo", "HP");
3 //Associative Array
4 $color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green");
5 //Multidimensional Array

6 $courses = array ( array("PHP",50), array("JQuery",15), array("AngularJS",20)


);
Q #8) What are the uses of explode() and implode() functions?
Answer:
explode() function is used to split a string into an array and implode() function is used to make
a string by combining the array elements.
Sample code:
1 $text = "I like programming";
2 print_r (explode(" ",$text));
3 $strarr = array('Pen','Pencil','Eraser');
4 echo implode(" ",$strarr);
Q #9) Which function can be used to exit from the script after displaying the error
message?
Answer:
You can use exit() or die() function to exit from the current script after displaying the error
message.
Sample code:
1 if(!fopen('t.txt','r'))
2 exit(" Unable to open the file");
Sample code:
1 if(!mysqli_connect('localhost','user','password'))
2 die(" Unable to connect with the database");
Q #10) Which function is used in PHP to check the data type of any variable?
Answer:
gettype() function is used to check the data type of any variable.

Sample code:
1 echo gettype(true).''; //boolean
2 echo gettype(10).''; //integer
3 echo gettype('Web Programming').''; //string
4 echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in PHP?
Answer:
You need to change the value of the max_execution_time directive in the php.ini file for
increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the value as
follows,
1 max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference’ in PHP?
Answer:
When the variable is passed as value then it is called pass variable by value.
Here, the main variable remains unchanged even when the passed variable changes.

Sample code:
1 function test($n) {
2 $n=$n+10;
3}
4
5 $m=5;
6 test($m);
7 echo $m;
When the variable is passed as a reference then it is called pass variable by reference. Here,
both the main variable and the passed variable share the same memory location and & is used
for reference.
So, if one variable changes then the other will also change.

Sample code:
1 function test(&$n) {
2 $n=$n+10;
3}
4 $m=5;
5 test($m);
6 echo $m;
Q #13) Explain type casting and type juggling.
Answer:
The way by which PHP can assign a particular data type for any variable is called typecasting.
The required type of variable is mentioned in the parenthesis before the variable.

Sample code:
1 $str = "10"; // $str is now string
2 $bool = (boolean) $str; // $bool is now boolean
PHP does not support data type for variable declaration. The type of the variable is changed
automatically based on the assigned value and it is called type juggling.

Sample code:
1 $val = 5; // $val is now number
2 $val = "500" //$val is now string
Q #14) How can you make a connection with MySQL server using PHP?
Answer:
You have to provide MySQL hostname, username and password to make a connection with the
MySQL server in mysqli_connect() method or declaring database object of the mysqli class.
Sample code:
1 $mysqli = mysqli_connect("localhost","username","password");
2 $mysqli = new mysqli("localhost","username","password");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer:
Many functions are available in PHP to retrieve the data from the MySQL database.

Few functions are mentioned below:


mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative
array.
Sample code:
1 // Associative or Numeric array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
4 echo "Name is $row[0]
5 ";
6 echo "Email is $row['email']
7 ";
mysqli_fetch_row() – It is used to fetch the records in a numeric array.
Sample code:
1 //Numeric array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row[0],$row[1]);
mysqli_fetch_assoc() – It is used to fetch the records in an associative array.
Sample code:
1 // Associative array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row["name"],$row["email"]);
mysqli_fetch_object() – It is used to fetch the records as an object.
Sample code:
1 // Object
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row->name,$row->email);
Q #16) What are the differences between mysqli_connect and mysqli_pconnect?
Answer:
mysqli_pconnect() function is used for making a persistence connection with the database that
does not terminate when the script ends.
mysqli_connect() function searches any existing persistence connection first and if no
persistence connection exists, then it will create a new database connection and terminate the
connection at the end of the script.
Sample code:
1 $DBconnection = mysqli_connect("localhost","username","password","dbname");
2 // Check for valid connection
3 if (mysqli_connect_errno())
4{
5 echo "Unable to connect with MySQL: " . mysqli_connect_error();
6}
mysqli_pconnect() function is depreciated in the new version of PHP, but you can create
persistence connection using mysqli_connect with the prefix p.
Q #17) Which function is used in PHP to count the total number of rows returned by any
query?
Answer:
mysqli_num_rows() function is used to count the total number of rows returned by the query.
Sample code:
1 $mysqli = mysqli_connect("hostname","username","password","DBname");
2 $result=mysqli_query($mysqli,"select * from employees");
3 $count=mysqli_num_rows($result);
Q #18) How can you create a session in PHP?
Answer:
session_start() function is used in PHP to create a session.
Sample code:
1 session_start(); //Start session
2 $_SESSION['USERNAME']='Fahmida'; //Set a session value
3 unset($_SESSION['USERNAME']; //delete session value
Q #19) What is the use of imagetypes() method?
Answer:
image types() function returns the list of supported images of the installed PHP version. You
can use this function to check if a particular image extension is supported by PHP or not.
Sample code:
1 //Check BMP extension is supported by PHP or not
2 if (imagetypes() &IMG_BMP) {
3 echo "BMP extension Support is enabled";
4}
Q #20) Which function you can use in PHP to open a file for reading or writing or for
both?
Answer:
You can use fopen() function to read or write or for doing both in PHP.
Sample code:
1 $file1 = fopen("myfile1.txt","r"); //Open for reading
2 $file2 = fopen("myfile2.txt","w"); //Open for writing
3 $file3 = fopen("myfile3.txt","r+"); //Open for reading and writing
Q #21) What is the difference between include() and require()?
Answer:
Both include() and require() function are used for including PHP script from one file to another
file. But there is a difference between these functions.
If any error occurs at the time of including a file using include() function, then it continues the
execution of the script after showing an error message. require() function stops the execution of
a script by displaying an error message if an error occurs.
Sample code:
1 if (!include(‘test.php’)) echo “Error in file inclusion”;
2 if (!require(‘test.php’)) echo “Error in file inclusion”;
Q #22) Which function is used in PHP to delete a file?
Answer:
unlink() function is used in PHP to delete any file.
Sample code:
1 unlink('filename');
Q #23) What is the use of strip_tags() method?
Answer:
strip_tags() function is used to retrieve the string from a text by omitting HTML, XML and PHP
tags. This function has one mandatory parameter and one optional parameter. The optional
parameter is used to accept particular tags.
Sample code:
1 //Remove all tags from the text
2 echo strip_tags("<b>PHP</b> is a popular <em>scripting</em> language");
3 //Remove all tags excluding <b> tag

4 echo strip_tags("<b>PHP</b> is a popular <em>scripting</em>


language","<b>");
Q #24) How can you send HTTP header to the client in PHP?
Answer:
header() function is used to send raw HTTP header to a client before any output is sent.
Sample code:
1 header('Location: http://www.your_domain/');
Q #25) Which functions are used to count the total number of array elements in PHP?
Answer:
count() and sizeof() functions can be used to count the total number of array elements in PHP.
Sample code:
1 $names=array(“Asa”,”Prinka”,”Abhijeet”);
2 echo count($names);
3 $marks=array(95,70,87);
4 echo sizeof($marks);
Q #26) What is the difference between substr() and strstr()?
Answer:
substr() function returns a part of the string based on the starting point and length. Length
parameter is optional for this function and if it is omitted then the remaining part of the string
from the starting point will be returned.
strstr() function searches the first occurrence of a string inside another string. The third
parameter of this function is optional and it is used to retrieve the part of the string that appears
before the first occurrence of the searching string.
Sample code:
1 echo substr("Computer Programming",9,7); //Returns “Program”
2 echo substr("Computer Programming",9); //Returns “Programming”
Sample code:
1 echo strstr("Learning Laravel 5!","Laravel"); //Returns Laravel 5!
2 echo strstr("Learning Laravel 5!","Laravel",true); //Returns Learning
Q #27) How can you upload a file using PHP?
Answer:
To upload a file by using PHP, you have to do the following tasks.

#1) Enable file_uploads directive


Open php.ini file and find out the file_uploads directive and make it on.

1 file_uploads = On
#2) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data">

<input type="file" name="upd" id="upd">

<input type="submit" value="Upload" name="upload">

</form>

#3) Write PHP script to upload the file


1 if (move_uploaded_file($_FILES["upd"]["tmp_name"], "Uploads/")) {
2 echo "The file ". basename( $_FILES["upd"]["name"]). " is uploaded.";
3 } else {
4 echo "There is an error in uploading.";
5}
Q #28) How can you declare a constant variable in PHP?
Answer:
define() function is used to declare a constant variable in PHP. Constant variable declares
without the $ symbol.
Sample code:
1 define("PI",3.14);
Q #29) Which function is used in PHP to search a particular value in an array?
Answer:
in_array() function is used to search a particular value in an array.
Sample code:
1 $languages = array("C#", "Java", "PHP", "VB.Net");
2 if (in_array("PHP", $languages)) {
3 echo "PHP is in the list";
4}
5 else {
6 echo "php is not in the list";
7}
Q #30) What is the use of $_REQUEST variable?
Answer:
The $_REQUEST variable is used to read the data from the submitted HTML form.
Sample code:
Here, the $_REQUEST variable is used to read the submitted form field with the name
‘username’. If the form is submitted without any value, then it will print as “Name is empty”,
otherwise it will print the submitted value.
1 <?php
2 if (isset($_POST['submit'])) {
3 // collect value of input field
4 $name = $_REQUEST['username'];
5 if (empty($name)) {
6 echo "Name is empty";
7 } else {
8 echo $name;
9 }
10 }
11 else
12 {
13 ?>
14 <form method="post" action="#">
15 Name: <input type="text" name="username">
16 <input type="submit" name="submit">
17 </form>
18 <?php } ?>
Q #34) Which operator is used to combine string values in PHP?
Answer:
Two or more string values can be combined by using ‘.’ operator.

Sample code:
1 $val1 = "Software ";
2 $val2 = "Testing";
3 echo $val1.$val2; // The output is “Software Testing”
Q #35) What is PEAR?
Answer:
The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of cost. It
contains different types of packages from different developers.

Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer:
Different type of errors can occur in PHP.

Some major error types are mentioned below:


Fatal Errors– The execution of the script stops when this error occurs.
Sample code:
In the following script, f1() function is declared but f2() function is called which is not declared.
The execution of the script will stop when f2() function will call. So, “Testing Fatal Error” will
not be printed.
1 function f1()
2 { echo "function 1";
3}
4 f2();
5 echo “Testing Fatal Error”;
Parse Errors– This type of error occurs when the coder uses a wrong syntax in the script.
Sample code:
Here, semicolon(;) is missing at the end of the first echo statement.

1 echo "This is a testing script<br/>"


2 echo "error";
Warning Errors- This type of error does not stop the execution of a script. It continues the
script even after displaying the error.
Sample code:
In the following script, if the test.txt file does not exist in the current location then a warning
message will display to show the error and print “Opening File” text by continuing the
execution.
1 $handler = fopen("test.txt","r");
2 echo "Opening File";
Notice Errors- This type of error shows a minor error of the script and continues the execution
after displaying the error.
Here, the variable, $a is defined but $b is not defined. So, a notice of undefined variable will
display for “echo $b” statement and print “Checking notice error” by continuing the script.
Sample code:
1 $a = 100;
2 echo $b;
3 echo "Checking notice error";
Q #37) Does PHP support multiple inheritances?
Answer:
PHP does not support multiple inheritances. To implement the features of multiple inheritances,
the interface is used in PHP.

Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book details to
add the feature of multiple inheritances in PHP.
1 interface Isbn {
2 public function setISBN($isbn);
3}
4 interface Type{
5 public function setType($type);
6}
7 class bookDetails implements Isbn, Type {
8 private $isbn;
9 private $type;
10 public function setISBN($isbn)
11 {
12 $this -> isbn = $isbn;
13 }
14 public function setType($type)
15 {
16 $this -> type = $type;
17 }
18 }
Q #38) What are the differences between session and cookie?
Answer:
The session is a global variable which is used in the server to store the session data. When a
new session creates the cookie with the session id is stored on the visitor’s computer. The
session variable can store more data than the cookie variable.

Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE
array. Session values are removed automatically when the visitor closes the browser and cookie
values are not removed automatically.
Q #39) What is the use of mysqli_real_escape_string() function?
Answer:
mysqli_real_escape_string() function is used to escape special characters from the string for
using a SQL statement

Sample code:
1 $DBconnection=mysqli_connect("localhost","username","password","dbname");
2 $productName = mysqli_real_escape_string($con, $_POST['proname']);
3 $ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the string?
Answer:
There are three functions in PHP to remove the whitespaces from the string.

trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.
Sample code:
1 $str = " Tutorials for your help";
2 $val1 = trim($str);
3 $val2 = ltrim($str);
4 $val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer:
A cookie file that is stored permanently in the browser is called a persistence cookie. It is not
secure and is mainly used for tracking a visitor for long times.

This type of cookie can be declared as follows,

setccookie ("cookie_name", "cookie_value", strtotime("+2 years");

Q #42) How can a cross-site scripting attack be prevented by PHP?


Answer:
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.

Q #43) Which PHP global variable is used for uploading a file?


Answer:
$_FILE[] array contains all the information of an uploaded file.

The use of various indexes of this array is mentioned below:


$_FILES[$fieldName][‘name’] – Keeps the original file name.
$_FILES[$fieldName][‘type’] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size’] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name’] – Keeps the temporary file name which is used to store the
file in the server.
$_FILES[$fieldName][‘error’] – Contains error code related to the error that appears during the
upload.
Q #44) What is meant by public, private, protected, static and final scopes?
Answer:
 Public– Variables, classes, and methods which are declared public can be accessed
from anywhere.
 Private– Variables, classes and methods which are declared private can be accessed
by the parent class only.
 Protected– Variables, classes, and methods which are declared protected can be
accessed by the parent and child classes only.
 Static– The variable which is declared static can keep the value after losing the scope.
 Final– This scope prevents the child class to declare the same item again.
Q #45) How can image properties be retrieved in PHP?
Answer:
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.
Q #46) What is the difference between abstract class and interface?
Answer:
 Abstract classes are used for closely related objects and interfaces are used for
unrelated objects.
 PHP class can implement multiple interfaces but can’t inherit multiple abstract classes.
 Common behavior can be implemented in the abstract class but not an interface.
Q #47) What is garbage collection?
Answer:
It is an automated feature of PHP.

When it runs, it removes all sessions data which are not accessed for a long time. It runs on
/tmp directory which is the default session directory.

PHP directives which are used for garbage collection include:


 session.gc_maxlifetime (default value, 1440)
 session.gc_probability (default value, 1)
 session.gc_divisor (default value, 100)
Q #48) Which library is used in PHP to do various types of Image work?
Answer:
Using GD library, various types of image work can be done in PHP. Image work includes
rotating image, cropping an image, creating image thumbnail etc.

Q #49) What is URL rewriting?


Answer:
Appending the session ID in every local URL of the requested page for keeping the session
information is called URL rewriting.

The disadvantages of this methods are, it doesn’t allow persistence between the sessions and,
the user can easily copy and paste the URL and send to another user.

Q #50) What is PDO?


Answer:
The full form of PDO is PHP Data Objects.
It is a lightweight PHP extension that uses consistence interface for accessing the database.
Using PDO, a developer can easily switch from one database server to the other. But it does not
support all the advanced features of the new MySQL server.

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 of MySQL?

MySQL database software is a client or server system which includes

 Multithreaded SQL server supporting various client programs and libraries


 Different backend
 Wide range of application programming interfaces and
 Administrative tools.
3. Why MySQL is used?

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. 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.

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.

1 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
1 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

1 SELECT COUNT (user_id) FROM users;


32. Is Mysql query is case sensitive?

No.

1 SELECT VERSION(), CURRENT_DATE;


2 SeLect version(), current_date;
3 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 %.


1 SELECT * FROM employee WHERE emp_name REGEXP "^b";
2 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:

1 mysql ;
2 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.

1 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:

1 SELECT * FROM
2 LIMIT 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.

Q #1) What is MySQL?


Answer:
MySQL is an open source DBMS which is developed and distributed by Oracle Corporation.

It is supported by most of the popular operating systems, such as Windows, Linux etc. It can be
used to develop a different type of applications but it is mainly used for developing web
applications.

MySQL uses GPL (GNU General Public License) license so that anyone can download and
install it for developing those applications which will be published or distributed freely. But if a
user wants to develop any commercial application using MySQL then he/she will need to buy
the commercial version of MySQL.

Q #2) What are the features of MySQL?


Answer:
MySQL has several useful features which make it a popular database management software.

Some important features of MySQL are mentioned below.


 It is reliable and easy to use too.
 It is the suitable database software for both large and small application.
 Anyone can install and use it at no cost.
 It is supported by many well-known programming languages, such as PHP, Java, C++,
PERL etc.
 It supports standard SQL (Structured Query Language).
 The open source license of MySQL is customizable. Hence, a developer can modify it
according to the requirements of the application.
Q #3) What is the default port number of MySQL?
Answer:
The default port number of MySQL is 3306.
Q #4) How can you find out the version of the installed MySQL?
Answer:
The version of the installed MySQL server can be found out easily by running the following
command from the MySQL prompt.

mysql> SHOW VARIABLES LIKE “%version%”;

Q #5) What are the advantages and disadvantages of using MySQL?


Answer:
There are several advantages of MySQL which are making it a more popular database system
now.
Some significant advantages and disadvantages of MySQL are mentioned below.

Advantages:
 It is well-known for its reliable and secure database management system. Transactional
tasks of the website can be done more securely by using this software.
 It supports different types of storage engines to store the data and it works faster for this
feature.
 It can handle millions of queries with a high-speed transactional process.
 It supports many advanced level database features, such as multi-level transaction, data
integrity, deadlock identification etc.
 Maintenance and debugging process are easier for this software.
Disadvantages:
 It is hard to make MySQL scalable.
 It is not suitable for a very large type of database.
 The uses of stored routine and trigger are limited to MySQL.
Q #6) What is the function of myisamchk?
Answer:
myisamchk is a useful database utility tool that is used to get information about MyISAM
database tables.

It is also used for checking, debugging, repairing and optimizing database tables. It is better to
use this command when the server is down or when the required tables are not in use by the
server.

Syntax:
myisamchk [OPTION] table_name…
The available options of this tool can be retrieved by using the following command.

myisamchk –help
To check or repair all MyISAM tables, the following command will be required for executing from
the database directory location.

myisamchk *.MYI
Q #7) What are the purposes of using ENUM and SET data types?
Answer:
ENUM data type is used in the MySQL database table to select any one value from the
predefined list.

The value of a particular field can be restricted by defining the predefined list as the field which
is declared as ENUM will not accept any value outside the list.

The SET data type is used to select one or more or all values from the predefined list. This data
type can also be used to restrict the field for inserting only the predefined list of values like
ENUM.

Example:
Run MySQL server from the command prompt and execute the following SQL commands to
know the use of ENUM and SET data type.
The following SQL commands create a new database named ‘newdb’ and select the database
for use.
CREATE DATABASE newdb;
USE newdb;

The following SQL command will create a table named clients with the fields ENUM and SET
data type.
1 CREATE TABLE clients (
2 id INT AUTO_INCREMENT PRIMARY KEY,
3 name VARCHAR(50),
4 membership ENUM('Silver', 'Gold', 'Diamond'),
5 interest SET('Movie', 'Music', 'Concert'));

Insert query will create two records in the table. ENUM field only accepts data from the defined
list.

‘Premium’ value does not exist on the ENUM list. Hence, the value of the ENUM field will be
empty for the second record. SET can accept multiple values and both the data will be inserted
in the second record.
1 INSERT INTO clients (name, membership,interest)
2 VALUES ('Sehnaz','Gold', 'Music'),
3 ('Sourav','Premium', 'Movie,Concert');
4 SELECT * FROM clients;
Q #8) What are the differences between a primary key and foreign key?
Answer:
Database table uses a primary key to identify each row uniquely. It is necessary to declare the
primary key on those tables that require to create a relationship among them. One or more
fields of a table can be declared as the primary key.

When the primary key of any table is used in another table as the primary key or another field
for making a database relation, then it is called a foreign key.

The differences between these two keys are mentioned below.


 The primary key uniquely identifies a record, whereas foreign key refers to the primary
key of another table.
 The primary key can never accept a NULL value but foreign key accepts a NULL value.
 When a record is inserted in a table that contains the primary key then it is not
necessary to insert the value on the table that contains this primary key field as the
foreign key.
 When a record is deleted from the table that contains the primary key then the
corresponding record must be deleted from the table containing the foreign key for data
consistency. But any record can be deleted from the table that contains a foreign key
without deleting a related record of another table.
Example:
Two tables named manufacturers and items will be created after executing the following two
SQL commands.
Here, the primary key of the manufacturers table is used as foreign key in the items table with
the field name manufacturer_id. Hence, the manufacturer_id field will contain only those
values that exist in the manufacturers table.
1 CREATE TABLE manufacturers (
2 id INT AUTO_INCREMENT PRIMARY KEY,
3 name VARCHAR(50));
4 CREATE TABLE items (
5 id INT AUTO_INCREMENT PRIMARY KEY,
6 name VARCHAR(50),
7 type VARCHAR(50),
8 brand VARCHAR(50),
9 manufacturer_id INT,
10 FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id));

Q #9) What are the differences between CHAR and VARCHAR data types?
Answer:
Both CHAR and VARCHAR data types are used to store string data in the field of the table.

The differences between these data types are mentioned below:


 CHAR data type is used to store fixed-length string data and VARCHAR data type is
used to store variable-length string data.
 The storage size of CHAR data type will always be the maximum length of this data type
and the storage size of VARCHAR will be the length of the inserted string data. Hence, it
is better to use the CHAR data type when the length of the string will be the same length
for all the records.
 CHAR is used to store small data whereas VARCHAR is used to store large data.
 CHAR works faster and VARCHAR works slower.
Example:
The following SQL statement will create a table named customers. In this table, the data type
of name field is VARCHAR and the data type of phone field is CHAR.
The size of the name field will depend on the length of the inserted value. The size of
the phone field will always be 14 characters even if the length of the inserted value is less than
14 characters.
1 CREATE TABLE customers (
2 id INT AUTO_INCREMENT PRIMARY KEY,
3 name VARCHAR(50),
4 phone CHAR(14))
Q #10) What is the purpose of using TIMESTAMP data type?
Answer:
A TIMESTAMP data type is used to store the combination of date and time value which is 19
characters long.

The format of TIMESTAMP is YYYY-MM-DD HH:MM: SS. It can store data from ‘1970-01-01
00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC. By default, the current date and time of the server
get inserted in the field of this data type when a new record is inserted or updated.

Q #11) What is the difference between mysql_fetch_array() and ysql_fetch_object() ?


Answer:
Both mysql_fetch_array() and mysql_fetch_object() are built-in methods of PHP to retrieve
records from MySQL database table.

The difference between these methods is that mysql_fetch_array() returns the result set as an
array and mysql_fetch_object() returns the result set as an object.

Example:
1 $result = mysql_query("SELECT id, name FROM clients");
2
3 //using mysql_fetch_array()
4 while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
5 printf("ID: %s Name: %s", $row[0], $row[1]);
6}
7
8 //using mysql_fetch_object()
9 while ($row = mysql_fetch_object($result)) {
10 printf("ID: %s Name: %s", $row->id, $row->name);
11 }
Q #12) How can you filter the duplicate data while retrieving records from the table?
Answer:
A DISTINCT keyword is used to filter the duplicate data from the table while retrieving the
records from a table.

Example:
The following SQL command shows all the records of the items table. The output shows that
the table contains duplicate values in the type field.
SELECT * from items;

The following SQL command will display the values of type field by removing the duplicate
values.
SELECT DISTINCT type from items;

Q #13) What is the difference between NOW() and CURRENT_DATE()?


Answer:
Both NOW() and CURRENT_DATE() are built-in MySQL methods. NOW() is used to show the
current date and time of the server and CURRENT_DATE() is used to show only the date of the
server.
SELECT now();
SELECT current_date();

Q #14) Which statement is used in a select query for partial matching?


Answer:
REGEXP and LIKE statements can be used in a select query for partial matching. REGEXP is
used to search records based on the pattern and LIKE is used to search any record by matching
any string at the beginning or end or middle of a particular field value.
Example:
First, check the existing records of the ‘clients' table by executing the select query.
SELECT * FROM clients;

Run SELECT query with REGEXP clause to search those records from the clients where the
client name starts with ‘S’
SELECT * FROM clients WHERE name REGEXP “^S”;
Run SELECT query with LIKE clause to search those records from the clients where the client
name starts with ‘A’
SELECT * FROM clients WHERE name LIKE “A%”;

Q #15) Which MySQL function is used to concatenate string?


Answer:
CONCAT() function is used to combine two or more string data. The use of this function is here
with an example.
Example:
The following SELECT query with CONCAT() function will combine five words, ‘Welcome ‘, ‘to’,
‘SoftwareTestingHelp’,’.’ and ‘com’.

SELECT CONCAT(‘Welcome ‘,to ‘,'SoftwareTestingHelp','.',com');

CONCAT() function can be used on any table as well. The following SELECT query will show
the output by combining two fields, brand and type of items table.
SELECT CONCAT(brand,'=>',type) from items;
Q #16) How can you change the name of any existing table by using the SQL statement?
Answer:
The following SQL command is used to rename an existing table of the database.

RENAME TABLE table_name TO new_name


Example:
The following command will show the table list of the newdb database.
SHOW TABLES;

The following rename command will rename the table items by new name products.
RENAME TABLE items TO products;
SHOW TABLES;

Q #17) How can you retrieve a portion of any column value by using a select query?
Answer:
SUBSTR() function is used to retrieve the portion of any column. The use of this function is
explained here with an example.
Example:
Here, the first select command is used to show all the records of the products table and the
second select command is executed using SUBSTR function and that prints only the first five
characters of the name field.

SELECT * FROM products;


SELECT SUBSTR(name,1,5) FROM products;

Q #18) What is the purpose of using a HEAP table?


Answer:
The table which uses a hashed index and stores in the memory is called HEAP table. It works
as a temporary table and it uses the indexes that make it faster than another table type.

When MySQL crashes for any reason then all the data stored in this table can be lost. It uses
fixed length data types. Hence BLOB and TEXT data types are not supported by this table. It is
a useful table for those MySQL tasks where speed is the most important factor and temporary
data is used.

Q #19) How can you add and remove any column of a table?
Answer:
The syntax for adding any column in an existing table is shown below.

ALTER TABLE table_name ADD COLUMN column_name column_definition


[FIRST|AFTER existing_column]
Example:
DESCRIBE command is used to show the structure of the products table.

DESCRIBE products;
The following ALTER command with ADD COLUMN clause will add a new field named ‘price' in
the table products.
ALTER TABLE products ADD COLUMN price DECIMAL(5,2);
DESCRIBE products;

The syntax for removing any column from an existing table is shown below.

ALTER TABLE table_name DROP COLUMN column_name;


Example:
The following ALTER command with a DROP COLUMN clause will remove the field named
‘brand' in the table ‘products'.
ALTER TABLE products DROP COLUMN brand;
DESCRIBE products;
Q #20) What is an index? How can an index be declared in MySQL?
Answer:
An index is a data structure of MySQL table that is used to speed up the queries.

It is used by the database search engine to find out the records faster. One or more fields of a
table can be used as an index key. Index key can be assigned at the time of table declaration or
can be assigned after creating the table.

Example:
username and email fields are set as the index in the following create table statement.
1 CREATE TABLE users(
2 username VARCHAR(50) PRIMARY KEY,
3 email VARCHAR(50) NOT NULL,
4 password VARCHAR(50) NOT NULL,
5 INDEX (username, email));

The following command will show the index key information of the ‘users' table.
SHOW INDEXES FROM users;
Q #21) What is meant by decimal (5,2)?
Answer:
A decimal data type is used in MySQL to store the fractional data.

The meaning of decimal (5,2) means that the total length of the fractional value is 5. The field
can contain 3 digits before the decimal point and 2 digits after the decimal point. If a user adds
any value larger than the defined length then it will insert 999.99 in the field.

The use of this data type is explained in the following example.

Example:
In the following insert query, 789.56 is inserted in the price field. This value is less than 1000
and the total digits with the fractional part are 5. So, this value is valid for this field.
1 INSERT INTO products (type, name, price, manufacturer_id)
2 VALUES ('Mobile', 'iPhone 8', 789.56, 1);
3 SELECT * FROM products;

In the following insert query, 34789.567 is set for the price field. Then this value is greater than
1000 and the total digits with fractional part are 8. So, the default value 999.99 is inserted in the
place of 34789.567.
1 INSERT INTO products (type, name, price, manufacturer_id)
2 VALUES('TV','Sony 32" Smart TV',34789.567, 2);
3 SELECT * FROM products;

Q #22) What is view? How can you create and drop view in MySQL?
Answer:
A view works as a virtual table that is used to store query and returns a result set when it is
called. An updatable view is also supported by MySQL.

The ways in which a view can be created or deleted in MySQL is shown in the following
examples.

Create View Example:


The following statement will create a view file named ‘client_list’ based on the table clients.
CREATE VIEW `client_list` AS SELECT `name` as ‘Name', `membership` as ‘Membership'
FROM `clients`;
Select statement will display the records of client_list value.
SELECT * FROM client_list;

Drop View Example:


Drop view statement will delete the view file. Select query will show an error after deleting the
view.
DROP VIEW client_list;
SELECT * FROM client_list;

Q #23) What is the function of mysqldump?


Answer:
mysqldump is an useful utility tool of MySQL that is used to dump one or more or all databases
from the server for backup or transfer to another database server.

Syntax:
For a single database,

mysqldump [OPTIONS] db_name [TABLES]


For multiple databases,

mysqldump [OPTIONS] –databases DB1 [DB2 DB3…]


For all databases,

mysqldump [OPTIONS] –all-databases


Example:
The following command will create a dump of the ‘newdb' database and export the content of
the database in the file, newdb.sql.
mysqldump –databases newdb > newdb.sql

Q #24) How can you change the password of a MySQL user?


Answer:
SET PASSWORD statement is used to change the password of a MySQL user.
Syntax:
SET PASSWORD FOR ‘username'@'hostname' = PASSWORD(‘password');

Example:
The following statement will set or change the root password.

SET PASSWORD FOR ‘root'@'localhost' = PASSWORD(‘123456');


Q #25) What is the difference between UNIX TIMESTAMP and MySQL TIMESTAMP?
Answer:
Both UNIX TIMESTAMP and MySQL TIMESTAMP are used to represent the date and time
value. The main difference between these values is that UNIX TIMESTAMP represents the
value by using 32-bits integers and MySQL TIMESTAMP represents the value in the human-
readable format.

Example:
A UNIX time value is used by FROM_UNIXTIME function in SELECT query to get the date and
time value in the human-readable format.

SELECT FROM_UNIXTIME (1596222320) AS ‘MySQLTIMESTAMP';

Date and time value is used by UNIX_TIMESTAMP function in SELECT query to get the date
and time value in the UNIX format.

SELECT UNIX_TIMESTAMP (‘2018-12-25 09:45:40') AS ‘UNIXTIMESTAMP';

Q #26) How can you import tables from a SQL file into a database by using the MySQL
client?
Answer:
Database tables can be imported into a database from a SQL file by using the following MySQL
statement.

mysql -u username -p database_name < sql_filename


Example:
If the root user’s password is empty, then the following command will import tables from
‘newdb.sql’ file into the database `mydb`.
mysql -u root mydb < newdb.sql

Q #27) What is the difference between Primary key and Unique key?
Answer:
Unique data is stored in the primary key and unique key fields. Primary key field never accepts
NULL value but unique key field accepts a NULL value.

Example:
In the users' table, id field is the primary key and email field is a unique key. Two records are
inserted in the table where the email field is NULL for the 2nd record. The records are inserted
properly as the unique field supports a NULL value.
1 INSERT INTO users (username, email, password)
2 VALUES('admin', 'admin@example.com', '7890'),
3 ('staff', 'NULL', '1234');
4 SELECT * FROM users;

Q #28) What is the purpose of using IFNULL() function?


Answer:
IFNULL() function takes two arguments. It returns the first argument value if the value of the first
argument is not NULL and it returns the second argument if the value of the first argument is
NULL.
Example:
Here, the first argument of IFNULL function is not NULL. So, the output is the first argument
value.

SELECT IFNULL (“Tutorial”, “fahmidasclassroom.com”);

Here, the first argument of IFNULL function is NULL. So, the output is NULL.

SELECT IFNULL (“NULL”, “fahmidasclassroom.com”);

Q #29) What is a join? Explain the different types of MySQL joins.


Answer:
The SQL statement that is used to make a connection between two or more tables based on the
matching columns is called a join. It is mainly used for complex queries.

Different types of SQL joins are mentioned below:


 Inner Join: It is a default join. It returns records when the values match in the joining
tables.
 Left Outer Join: It returns all the records from the left table based on the matched
records from the right table.
 Right Outer Join: It returns all the records from the right table based on the matched
records from the left table.
 Full Outer Join: It returns all the records that match from the left or right table.
Example:
Two tables, manufacturers and products are used in this example to show the use of INNER
JOIN. Here, SELECT queries are used to show the current records of these two tables.
SELECT * FROM manufacturers;
SELECT * FROM products;
INNER JOIN is used in the following SELECT query where all the id and name of products table
will be displayed based on matching manufacturer_id of the products with an id of
the manufacturerstable.
1 SELECT products.id, products.name
2 FROM products
3 INNER JOIN manufacturers ON manufacturers.id= products.manufacturer_id;

Q #30) How can you retrieve a particular number of records from a table?
Answer:
LIMIT clause is used with the SQL statement to retrieve a particular number of records from a
table. From which record and how many records will be retrieved are defined by the LIMIT
clause.
Syntax:
LIMIT starting_number, number_of_rows
Example:
Products table has 5 records which are displayed by the first select query and the second select
query is used to display the records from 2nd to 3rd by using LIMIT 1, 2.
SELECT * FROM products;
SELECT * FROM products LIMIT 1, 2;

Q #31) How can you export the table as an XML file in MySQL?
Answer:
‘-X’ option is used with `mysql` command for exporting the file as XML. The following statement
will export any table from a database as an XML file.

mysql -u username -X -e “SELECT query” database_name


Example:
The following command will export the data of the items table into an xmlData.xml file.
mysql -u root -X -e “SELECT * from products” newdb > xmlData.xml

Q #32) What is a CSV table?


Answer:
MySQL table that uses CSV storage engine is called a CSV table. Data are stored as comma-
separated values in the CSV table. MySQL server creates a data file with an extension ‘.csv’ to
store the content of the CSV table.

Example:
The following create statement will create a CSV file named book.

CREATE TABLE book ( id INT NOT NULL) ENGINE=CSV;


Q #33) How can you calculate the sum of any column of a table?
Answer:
SUM() function is used to calculate the sum of any column.
Syntax:
SUM(DISTINCT expression)

Example:
Products table has a numeric field named, price. In this example, the SUM() function is used to
calculate the total value of the price field.
1 SELECT * FROM products;
2 SELECT SUM(price) as total FROM products;

Q #34) How can you count the total number of records of any table?
Answer:
COUNT() function is used to count the total number of records of any table.
Syntax:
COUNT(expression)

Example:
The following select query is used to count the total number of records of the products table.
SELECT COUNT(*) as `Total Records` FROM products;
Q #35) Explain the difference between delete and truncate.
Answer:
Both DELETE and TRUNCATE commands are used to delete the records from any database
table. However, there are some significant differences between these commands. If the table
contains AUTO_INCREMENT PRIMARY KEY field then the effect of these commands can be
shown properly.

Two differences between these commands are mentioned below.


#1) DELETE command is used to delete a single or multiple or all the records from the table.
TRUNCATE command is used to delete all the records from the table or make the table empty.
#2) When DELETE command is used to delete all the records from the table then it doesn’t re-
initialize the table. So, AUTO_INCREMENT field does not count from one when the user inserts
any record.
But when all the records of any table are deleted by using TRUNCATE command then it re-
initializes the table and a new record will start from one for the AUTO_INCREMENT field.

Example:
Previously created users table is used in this example.

First, the SELECT query will show all the records of the users table. DELETE query will delete
all the records from the user's table. INSERT query will insert a new record into the users table.
After insert, if the SELECT query executes again then it will be shown that a new id is
calculated after the deleted id.
1 SELECT * FROM users;
2 DELETE FROM users;
3 INSERT INTO users (username, email)
4 VALUES ('Durjoy', 'durjoy@gmail.com');
5 SELECT * FROM users;
Currently, there are two records in the users table and when a new record is inserted after
deleting all the records then the new id is 3, and not 1.
Same queries are executed in this part, just used TRUNCATE statement in place of DELETE. It
is shown that the id value of the new record is 1.

1 TRUNCATE table users;


2 INSERT INTO users (username, email)
3 VALUES ('Farheen', 'farheen@gmail.com');
4 SELECT * FROM users;
Q #36) What is a storage engine? What are the differences between InnoDB and MyISAM
engines?
Answer:
One of the major components of the MySQL server is the storage engine for doing different
types of database operations. Each database table created is based on the specific storage
engine.

MySQL supports two types of storage engines i.e transactional and non-transactional.
InnoDB is the default storage engine of MySQL which is a transactional storage engine.
MyISAM storage engine is a non-transactional storage engine.
The differences between InnoDB and MyISAM storage engines are discussed below:
 MyISAM supports FULLTEXT index but InnoDB doesn’t support FULLTEXT index.
 MyISAM is faster and InnoDB is slower.
 InnoDB supports ACID (Atomicity, Consistency, Isolation, and Durability) property but
MyISAM doesn’t.
 InnoDB supports row-level locking and MyISAM support table-level locking.
 InnoDB is suitable for large database and MyISAM is suitable for a small database.
Q #37) What is a transaction? Describe MySQL transaction properties.
Answer:
When a group of database operations is done as a single unit then it is called a transaction. If
any task of the transactional tasks remains incomplete then the transaction will not succeed.
Hence, it is mandatory to complete all the tasks of a transaction to make the transaction
successful.

A transaction has four properties which are known as ACID property. These properties are
described below.

 Atomicity: It ensures that all the tasks of a transaction will be completed successfully
otherwise all the completed tasks will be rolled back to the previous state for any failure.
 Consistency: It ensures that the database state must be changed accurately for the
committed transaction.
 Isolation: It ensures that all the tasks of a transaction will be done independently and
transparently.
 Durability: It ensures that all the committed transaction is consistent for any type of
system failure.
Q #38) What are the functions of commit and rollback statements?
Answer:
Commit is a transaction command that executes when all the tasks of a transaction are
completed successfully. It will modify the database permanently to confirm the transaction.

Syntax:
COMMIT;

Rollback is another transactional command that executes when any of the transactional tasks
becomes unsuccessful and undoes all the changes that are made by any transactional task to
make the transaction unsuccessful.

Syntax:
ROLLBACK;
Q #39) What is the difference between MyISAM static and MyISAM dynamic?
Answer:
MyISAM static and MyISAM dynamic are the variations of the MyISAM storage engine. The
differences between these tables are mentioned below.

 All the fields of MyISAM static table are of a fixed length and MyISAM dynamic table
accepts variable length fields such as BLOB, TEXT etc.
 After data corruption, it is easier to restore MyISAM static table than MyISAM dynamic
table.
Q #40) What is a trigger? How you can create a trigger in MySQL?
Answer:
One of the important features of the MySQL database is a trigger that executes automatically
when a particular database event occurs.

It fires after or before the execution of an insert or update or delete statement. It is a very useful
option when a database user wants to do some database operations automatically.

Trigger Example:
If you want to delete the items of a supplier from the items table automatically after deleting the
entry of the particular supplier from the ‘suppliers' table then write the trigger in the following
way.
Example:
This is an example of after delete trigger that will fire automatically when any record is removed
from the manufacturer table and deletes all the records from the products table where the
deleted id of the manufacturer table matches with the manufacturer_id field of
the products table.
1 DELIMITER //
2 CREATE TRIGGER manufacturer_after_delete
3 AFTER DELETE
4 ON manufacturers FOR EACH ROW
5 BEGIN
6 DELETE FROM products WHERE products.manufacturers_id = OLD.id;
7 END;
8 //
Laravel Interview Questions And Answers
Laravel Interview Questions

Laravel is an Open source software

PHP web framework, created for the development of web


Laravel is a
applications.

Laravel follows Model–view–controller (MVC) architectural pattern.

Laravel created by Taylor Otwell

Laravel Licence MIT License

Laravel has
PHP 7
written in

1) What is the Laravel?

A) Laravel is an open-source PHP web framework, created for the development of web
applications following the model–view–controller (MVC) architectural pattern.

2) What is Laravel Horizon?

A) Laravel Horizon provides a beautiful dashboard and code-driven configuration for


your Redis queues.

3) What is Laravel Dusk?

A) Laravel Dusk provides an expressive, easy-to-use browser automation and testing


API. You’ll love it.
4) What is Laravel Echo?

A) Event broadcasting, evolved. Bring the power of WebSockets to your application


without the complexity.

5) How do you install Laravel?

A) Laravel utilizes Composer to manage its dependencies. So, before using Laravel,
make sure we have Composer installed on your machine.

6) What is Composer Tool?

A) Composer is a tool for dependency management in PHP. It allows you to declare the
libraries your project depends on and it will manage (install/update) them for you.

7) What is Laravel service container?

A) The Laravel service container is a powerful tool for managing class dependencies and
performing dependency injection. Dependency injection is a fancy phrase that
essentially means this: class dependencies are “injected” into the class via the
constructor or, in some cases, “setter” methods.

8) What is Binding?

A) Within a service provider, we always have access to the container via the $this->app
property. We can register a binding using the bind method, passing the class or interface
name that we wish to register along with a Closure that returns an instance of the class:

$this->app->bind(‘HelpSpot\API’, function ($app) {


return new HelpSpot\API($app->make(‘HttpClient’));
});

9) Explain Binding A Singleton?

A) The singleton method binds a class or interface into the container that should only be
resolved one time. Once a singleton binding is resolved, the same object instance will be
returned on subsequent calls into the container.

10) Explain Binding Instances?


A) You may also bind an existing object instance into the container using the instance
method. The given instance will always be returned on subsequent calls into the
container:

$api = new HelpSpot\API(new HttpClient);

$this->app->instance(‘HelpSpot\API’, $api);

Top 65 Laravel Interview Questions

Laravel Interview Questions # 11) Explain Binding Primitives?

A) Sometimes you may have a class that receives some injected classes, but also needs
an injected primitive value such as an integer. You may easily use contextual binding to
inject any value your class may need:

$this->app->when(‘App\Http\Controllers\UserController’)
->needs(‘$variableName’)
->give($value);

Laravel Interview Questions # 12) Explain Contextual Binding and how does
it work?

A) Sometimes you may have two classes that utilize the same interface, but you wish to
inject different implementations into each class. For example, two controllers may
depend on different implementations of the
Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a simple, fluent
interface for defining this behavior:

use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;

$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘local’);
});
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘s3’);
});

Laravel Interview Questions # 13) What is Tagging?

A) Occasionally, you may need to resolve all of a certain “category” of binding. For
example, perhaps you are building a report aggregator that receives an array of many
different Report interface implementations. After registering the Report
implementations, you can assign them a tag using the tag method:

$this->app->bind(‘SpeedReport’, function () {
//
});

$this->app->bind(‘MemoryReport’, function () {
//
});

$this->app->tag([‘SpeedReport’, ‘MemoryReport’], ‘reports’);


Once the services have been tagged, you may easily resolve them all via the tagged
method:

$this->app->bind(‘ReportAggregator’, function ($app) {


return new ReportAggregator($app->tagged(‘reports’));
});

Laravel Interview Questions # 14) Explain Extending Bindings?

A) The extend method allows the modification of resolved services. For example, when a
service is resolved, you may run additional code to decorate or configure the service. The
extend method accepts a Closure, which should return the modified service, as its only
argument:

$this->app->extend(Service::class, function($service) {
return new DecoratedService($service);
});

Laravel Interview Questions # 15) What is the make Method?


A) You may use the make method to resolve a class instance out of the container. The
make method accepts the name of the class or interface you wish to resolve:

$api = $this->app->make(‘HelpSpot\API’);

Laravel Interview Questions # 16) What are service providers?

A) Service providers are the central place of all Laravel application bootstrapping. Your
own application, as well as all of Laravel’s core services are bootstrapped via service
providers.

Laravel Interview Questions # 17) What is Register Method?

A) within the register method, you should only bind things into the service container.
You should never attempt to register any event listeners, routes, or any other piece of
functionality within the register method.

Laravel Interview Questions # 18) Explain the bindings And singletons


Properties?

A) If your service provider registers many simple bindings, you may wish to use the
bindings and singletons properties instead of manually registering each container
binding. When the service provider is loaded by the framework, it will automatically
check for these properties and register their bindings

Laravel Interview Questions # 19) What is the Boot Method?

A) if we need to register a view composer within our service provider? This should be
done within the boot method. This method is called after all other service providers have
been registered, meaning you have access to all other services that have been registered
by the framework.

Laravel Interview Questions # 20) Where do you regiser service providers?

A) All service providers are registered in the config/app.php configuration file. This file
contains a providers array where you can list the class names of your service providers.

PHP Laravel Interview Questions And Answers

Laravel Interview Questions # 21) How do you register service providers?


A) To register your provider, add it to the array:

‘providers’ => [
// Other Service Providers

App\Providers\ComposerServiceProvider::class,
],

Laravel Interview Questions # 22) What are Facades?

A) Facades provide a “static” interface to classes that are available in the application’s
service container.

Laravel Interview Questions # 23) Where Laravel’s facades are defined?

A) All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace

Laravel Interview Questions # 24) What are the benefits of Facades?

A) Facades have many benefits. They provide a terse, memorable syntax that allows you
to use Laravel’s features without remembering long class names that must be injected or
configured manually. Furthermore, because of their unique usage of PHP’s dynamic
methods, they are easy to test.

Laravel Interview Questions # 25) Difference between Facades Vs.


Dependency Injection?

A) One of the primary benefits of dependency injection is the ability to swap


implementations of the injected class. This is useful during testing since you can inject a
mock or stub and assert that various methods were called on the stub.

Typically, it would not be possible to mock or stub a truly static class method. However,
since facades use dynamic methods to proxy method calls to objects resolved from the
service container, we actually can test facades just as we would test an injected class
instance.

Laravel Interview Questions # 26) What is the difference between


FacadesVs Helper Functions?
A) In addition to facades, Laravel includes a variety of “helper” functions which can
perform common tasks like generating views, firing events, dispatching jobs, or sending
HTTP responses. Many of these helper functions perform the same function as a
corresponding facade.

Laravel Interview Questions # 27) What are Laravel’s Contracts?

A) Laravel’s Contracts are a set of interfaces that define the core services provided by the
framework. For example, a Illuminate\Contracts\Queue\Queue contract defines the
methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer
contract defines the methods needed for sending e-mail.

Laravel Interview Questions # 28) What is the difference between Contracts


Vs Facades?

A) Laravel’s facades and helper functions provide a simple way of utilizing Laravel’s
services without needing to type-hint and resolve contracts out of the service container.
In most cases, each facade has an equivalent contract.

Unlike facades, which do not require you to require them in your class’ constructor,
contracts allow you to define explicit dependencies for your classes. Some developers
prefer to explicitly define their dependencies in this way and therefore prefer to use
contracts, while other developers enjoy the convenience of facades.

Laravel Interview Questions # 29) What is Routing in Laravel?

A) The most basic Laravel routes accept a URI and a Closure, providing a very simple
and expressive method of defining routes:

Route::get(‘foo’, function () {
return ‘Hello World’;
});

Laravel Interview Questions # 30) Where do you locate Route files?

A) All Laravel routes are defined in your route files, which are located in the routes
directory.

Laravel PHP Developer Interview Questions


Laravel Interview Questions # 31) What are the available Router Methods?

A) The router allows you to register routes that respond to any HTTP verb:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Laravel Interview Questions # 32) What is CSRF Protection?

A) aravel makes it easy to protect your application from cross-site request forgery
(CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby
unauthorized commands are performed on behalf of an authenticated user.

Laravel Interview Questions # 33) What is CSRF Protection Token?

A) Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in the
web routes file should include a CSRF token field. Otherwise, the request will be
rejected.

<form method=”POST” action=”/profile”>


@csrf

</form>

Laravel Interview Questions # 34) What is Redirect Routes?

A) If you are defining a route that redirects to another URI, you may use the
Route::redirect method.

Route::redirect(‘/here’, ‘/there’, 301);

Laravel Interview Questions # 35) What is View Routes?

A) If your route only needs to return a view, you may use the Route:: view method. The
view method accepts a URI as its first argument and a view name as its second
argument. In addition, you may provide an array of data to pass to the view as an
optional third argument.
Route::view(‘/welcome’, ‘welcome’);

Route::view(‘/welcome’, ‘welcome’, [‘name’ => ‘Taylor’]);

Laravel Interview Questions # 36) What is Named Routes?

A) Named routes allow the convenient generation of URLs or redirects for specific
routes. You may specify a name for a route by chaining the name method onto the route
definition:

Route::get(‘user/profile’, function () {
//
})->name(‘profile’);

Laravel Interview Questions # 37) What are Route Groups?

A) Route groups allow you to share route attributes, such as middleware or namespaces,
across a large number of routes without needing to define those attributes on each
individual route.

38) What is Route Model Binding?

A) When injecting a model ID to a route or controller action, you will often query to
retrieve the model that corresponds to that ID. Laravel route model binding provides a
convenient way to automatically inject the model instances directly into your routes.

Laravel Interview Questions # 39) What is Rate Limiting?

A) Laravel includes a middleware to rate limit access to routes within your application.
To get started, assign the throttle middleware to a route or a group of routes.

The throttle middleware accepts two parameters that determine the maximum number
of requests that can be made in a given number of minutes. For example, let’s specify
that an authenticated user may access the following group of routes 60 times per
minute:

Route::middleware(‘auth:api’, ‘throttle:60,1’)->group(function () {
Route::get(‘/user’, function () {
//
});
});
Laravel Interview Questions # 40) What is Middleware?

A) Middleware provide a convenient mechanism for filtering HTTP requests entering


your application.

Advanced Laravel Interview Questions And Answers

41) How do you define Middleware?

A) To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware CheckAge

This command will place a new CheckAge class within your app/Http/Middleware
directory.

42) What are Middleware Groups?

A) Sometimes you may want to group several middleware under a single key to make
them easier to assign to routes. You may do this using the $middlewareGroups property
of your HTTP kernel.

43) What is X-CSRF-TOKEN?

A) In addition to checking for the CSRF token as a POST parameter, the


VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header.
You could, for example, store the token in a HTML meta tag:

<meta name=”csrf-token” content=”{{ csrf_token() }}”>

44) What is X-XSRF-TOKEN?

A) Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is included with
each response generated by the framework. You can use the cookie value to set the X-
XSRF-TOKEN request header.

45) What is Response in Laravel?


A) All routes and controllers should return a response to be sent back to the user’s
browser. Laravel provides several different ways to return responses. The most basic
response is returning a string from a route or controller. The framework will
automatically convert the string into a full HTTP response:

Route::get(‘/’, function () {
return ‘Hello World’;
});

46) What are Redirect responses?

A) Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and


contain the proper headers needed to redirect the user to another URL. There are
several ways to generate a RedirectResponse instance. The simplest method is to use the
global redirect helper:

Route::get(‘dashboard’, function () {
return redirect(‘home/dashboard’);
});

47) What is Response Macros?

A) If you would like to define a custom response that you can re-use in a variety of your
routes and controllers, you may use the macro method on the Response facade.

48) What is View?

A) Views contain the HTML served by your application and separate your controller /
application logic from your presentation logic. Views are stored in the resources/views
directory. A simple view might look something like this:

<!– View stored in resources/views/greeting.blade.php –>

<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>

48) What are View Composers?


A) View composers are callbacks or class methods that are called when a view is
rendered. If you have data that you want to be bound to a view each time that view is
rendered, a view composer can help you organize that logic into a single location.

49) What are View Creators?

A) View creators are very similar to view composers; however, they are executed
immediately after the view is instantiated instead of waiting until the view is about to
render. To register a view creator, use the creator method:

View::creator(‘profile’, ‘App\Http\ViewCreators\ProfileCreator’);

50) How do you generate URLs?

A) Laravel provides several helpers to assist you in generating URLs for your
application. Of course, these are mainly helpful when building links in your templates
and API responses, or when generating redirect responses to another part of your
application.

Laravel Interview Questions For 2, 3, 4, 5 Years Experience

51) What is url helper?

A) The url helper may be used to generate arbitrary URLs for your application. The
generated URL will automatically use the scheme (HTTP or HTTPS) and host from the
current request:

$post = App\Post::find(1);
echo url(“/posts/{$post->id}”);
// http://example.com/posts/1
52) Exceptions are handled by which class?
A) All exceptions in Laravel are handled by the App\Exceptions\Handler class. This
class contains two methods: report and render.

53) What is report method?

A) The report method is used to log exceptions or send them to an external service like
Bugsnag or Sentry. By default, the report method passes the exception to the base class
where the exception is logged. However, you are free to log exceptions however you
wish.

54) What is the render method?

A) The render methos is responsible for converting a given exception into an HTTP
response that should be sent back to the browser. By default, the exception is passed to
the base class which generates a response for you.

55) What are HTTP Exceptions?

A) Some exceptions describe HTTP error codes from the server. For example, this may
be a “page not found” error (404), an “unauthorized error” (401) or even a developer
generated 500 error.

56) What is Monolog library?

A) Laravel utilizes the Monolog library, which provides support for a variety of powerful
log handlers. Laravel makes it a cinch to configure these handlers, allowing you to mix
and match them to customize your application’s log handling.

57) What is stack channel?

A) By default, Laravel will use the stack channel when logging messages. The stack
channel is used to aggregate multiple log channels into a single channel.

58) What are Blade Templates?

A) Blade is the simple, yet powerful templating engine provided with Laravel. Unlike
other popular PHP templating engines, Blade does not restrict you from using plain
PHP code in your views.

59) Where is the authentication configuration file is located in Laravel?

A) The authentication configuration file is located at config/auth.php, which contains


several well documented options for tweaking the behavior of the authentication
services.

60) What is fluent query builder in Laravel?


A) Laravel’s database query builder provides a convenient, fluent interface to creating
and running database queries. It can be used to perform most database operations in
your application and works on all supported database systems.

The Laravel query builder uses PDO parameter binding to protect your application
against SQL injection attacks. There is no need to clean strings being passed as bindings.

61) What is Eloquent ORM in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord
implementation for working with your database. Each database table has a
corresponding “Model” which is used to interact with that table. Models allow you to
query for data in your tables, as well as insert new records into the table.

62) Laravle supports which databases?

A) Laravel makes interacting with databases extremely simple across a variety of


database backends using either raw SQL, the fluent query builder, and the Eloquent
ORM. Currently, Laravel supports four databases:

MySQL
PostgreSQL
SQLite
SQL Server

63) Where do you locate database configuration file?

A) The database configuration for your application is located at config/database.php. In


this file you may define all of your database connections, as well as specify which
connection should be used by default.

64) What is Redis?

A) Redis is an open source, advanced key-value store. It is often referred to as a data


structure server since keys can contain strings, hashes, lists, sets, and sorted sets.

65) Can you explain about Serialization?

A) When building JSON APIs, you will often need to convert your models and
relationships to arrays or JSON. Eloquent includes convenient methods for making
these conversions, as well as controlling which attributes are included in your
serializations.

Serializing To Arrays – To convert a model and its loaded relationships to an array, you
should use the toArray method.

$user = App\User::with(‘roles’)->first();
return $user->toArray();
You may also convert entire collections of models to arrays:
$users = App\User::all();
Serializing To JSON – To convert a model to JSON, you should use the toJson method.
Like toArray, the toJson method is recursive, so all attributes and relations will be
converted to JSON:
$user = App\User::find(1);
return $user->toJson();
return $users->toArray();

1) What is GIT?

GIT is a distributed version control system and source code management (SCM) system with an
emphasis to handle small and large projects with speed and efficiency.

2) What is a repository in GIT?

A repository contains a directory named .git, where git keeps all of its metadata for the
repository. The content of the .git directory are private to git.

3) What is the command you can use to write a commit message?

The command that is used to write a commit message is “git commit –a”. The –a on the
command line instructs git to commit the new content of all tracked files that have been
modified. You can use “git add<file>” before git commit –a if new files need to be committed for
the first time.

4) What is the difference between GIT and SVN?

The difference between GIT and SVN is

a) Git is less preferred for handling extremely large files or frequently changing binary files
while SVN can handle multiple projects stored in the same repository.

b) GIT does not support ‘commits’ across multiple branches or tags. Subversion allows the
creation of folders at any location in the repository layout.
c) Gits are unchangeable, while Subversion allows committers to treat a tag as a branch
and to create multiple revisions under a tag root.

5) What are the advantages of using GIT?

a) Data redundancy and replication

b) High availability

c) Only one.git directory per repository

d) Superior disk utilization and network performance

e) Collaboration friendly

f) Any sort of projects can use GIT

6) What language is used in GIT?

GIT is fast, and ‘C’ language makes this possible by reducing the overhead of runtimes
associated with higher languages.

7) What is the function of ‘GIT PUSH’ in GIT?

‘GIT PUSH’ updates remote refs along with associated objects.

8) Why GIT better than Subversion?

GIT is an open source version control system; it will allow you to run ‘versions’ of a project,
which show the changes that were made to the code overtime also it allows you keep the
backtrack if necessary and undo those changes. Multiple developers can checkout, and upload
changes and each change can then be attributed to a specific developer.

9) What is “Staging Area” or “Index” in GIT?

Before completing the commits, it can be formatted and reviewed in an intermediate area known
as ‘Staging Area’ or ‘Index’.

10) What is GIT stash?

GIT stash takes the current state of the working directory and index and puts in on the stack for
later and gives you back a clean working directory. So in case if you are in the middle of
something and need to jump over to the other job, and at the same time you don’t want to lose
your current edits then you can use GIT stash.

11) What is GIT stash drop?

When you are done with the stashed item or want to remove it from the list, run the git ‘stash
drop’ command. It will remove the last added stash item by default, and it can also remove a
specific item if you include as an argument.

12) How will you know in GIT if a branch has been already merged into master?

Git branch—merged lists the branches that have been merged into the current branch
Git branch—-no merged lists the branches that have not been merged

13) What is the function of git clone?

The git clone command creates a copy of an existing Git repository. To get the copy of a central
repository, ‘cloning’ is the most common way used by programmers.

14) What is the function of ‘git config’?

The ‘git config’ command is a convenient way to set configuration options for your Git
installation. Behaviour of a repository, user info, preferences etc. can be defined through this
command.

15) What does commit object contain?

a) A set of files, representing the state of a project at a given point of time

b) Reference to parent commit objects

c) An SHAI name, a 40 character string that uniquely identifies the commit object.

16) How can you create a repository in Git?

In Git, to create a repository, create a directory for the project if it does not exist, and then run
command “git init”. By running this command .git directory will be created in the project
directory, the directory does not need to be empty.

17) What is ‘head’ in git and how many heads can be created in a repository?

A ‘head’ is simply a reference to a commit object. In every repository, there is a default head
referred as “Master”. A repository can contain any number of heads.

18) What is the purpose of branching in GIT?

The purpose of branching in GIT is that you can create your own branch and jump between
those branches. It will allow you to go to your previous work keeping your recent work intact.

19) What is the common branching pattern in GIT?

The common way of creating branch in GIT is to maintain one as “Main“

branch and create another branch to implement new features. This pattern is particularly useful
when there are multiple developers working on a single project.

20) How can you bring a new feature in the main branch?

To bring a new feature in the main branch, you can use a command “git merge” or “git pull
command”.

21) What is a ‘conflict’ in git?

A ‘conflict’ arises when the commit that has to be merged has some change in one place, and
the current commit also has a change at the same place. Git will not be able to predict which
change should take precedence.
22) How can conflict in git resolved?

To resolve the conflict in git, edit the files to fix the conflicting changes and then add the
resolved files by running “git add” after that to commit the repaired merge, run “git commit”. Git
remembers that you are in the middle of a merger, so it sets the parents of the commit correctly.

23) To delete a branch what is the command that is used?

Once your development branch is merged into the main branch, you don’t need

development branch. To delete a branch use, the command “git branch –d [head]”.

24) What is another option for merging in git?

“Rebasing” is an alternative to merging in git.

25) What is the syntax for “Rebasing” in Git?

The syntax used for rebase is “git rebase [new-commit] “

26) What is the difference between ‘git remote’ and ‘git clone’?

‘git remote add’ just creates an entry in your git config that specifies a name for a particular
URL. While, ‘git clone’ creates a new git repository by copying and existing one located at the
URI.

27) What is GIT version control?

With the help of GIT version control, you can track the history of a collection of files and includes
the functionality to revert the collection of files to another version. Each version captures a
snapshot of the file system at a certain point of time. A collection of files and their complete
history are stored in a repository.

28) Mention some of the best graphical GIT client for LINUX?

Some of the best GIT client for LINUX is

a) Git Cola

b) Git-g

c) Smart git

d) Giggle

e) Git GUI

f) qGit

29) What is Subgit? Why to use Subgit?

‘Subgit’ is a tool for a smooth, stress-free SVN to Git migration. Subgit is a solution for a
company -wide migration from SVN to Git that is:

a) It is much better than git-svn


b) No requirement to change the infrastructure that is already placed

c) Allows to use all git and all sub-version features

d) Provides genuine stress –free migration experience.

30) What is the function of ‘git diff ’ in git?

‘git diff ’ shows the changes between commits, commit and working tree etc.

31) What is ‘git status’ is used for?

As ‘Git Status’ shows you the difference between the working directory and the index, it is
helpful in understanding a git more comprehensively.

32) What is the difference between the ‘git diff ’and ‘git status’?

‘git diff’ is similar to ‘git status’, but it shows the differences between various commits and also
between the working directory and index.

33) What is the function of ‘git checkout’ in git?

A ‘git checkout’ command is used to update directories or specific files in your working tree with
those from another branch without merging it in the whole branch.

34) What is the function of ‘git rm’?

To remove the file from the staging area and also off your disk ‘git rm’ is used.

35) What is the function of ‘git stash apply’?

When you want to continue working where you have left your work, ‘git stash apply’ command is
used to bring back the saved changes onto the working directory.

36) What is the use of ‘git log’?

To find specific commits in your project history- by author, date, content or history ‘git log’ is
used.

37) What is ‘git add’ is used for?

‘git add’ adds file changes in your existing directory to your index.

38) What is the function of ‘git reset’?

The function of ‘Git Reset’ is to reset your index as well as the working directory to the state of
your last commit.

39) What is git Is-tree?

‘git Is-tree’ represents a tree object including the mode and the name of each item and the SHA-
1 value of the blob or the tree.

40) How git instaweb is used?


‘Git Instaweb’ automatically directs a web browser and runs webserver with an interface into
your local repository.

41) What does ‘hooks’ consist of in git?

This directory consists of Shell scripts which are activated after running the corresponding Git
commands. For example, git will try to execute the post-commit script after you run a commit.

42) Explain what is commit message?

Commit message is a feature of git which appears when you commit a change. Git provides you
a text editor where you can enter the modifications made in commits.

43) How can you fix a broken commit?

To fix any broken commit, you will use the command “git commit—amend”. By running this
command, you can fix the broken commit message in the editor.

44) Why is it advisable to create an additional commit rather than amending an existing commit?

There are couple of reason

a) The amend operation will destroy the state that was previously saved in a commit. If it’s
just the commit message being changed then that’s not an issue. But if the contents are being
amended then chances of eliminating something important remains more.

b) Abusing “git commit- amend” can cause a small commit to grow and acquire unrelated
changes.

45) What is ‘bare repository’ in GIT?

To co-ordinate with the distributed development and developers team, especially when you are
working on a project from multiple computers ‘Bare Repository’ is used. A bare repository
comprises of a version history of your code.

46) Name a few Git repository hosting services


 Pikacode
 Visual Studio Online
 GitHub
 GitEnterprise
 SourceForge.net

Das könnte Ihnen auch gefallen