IV – Others

1. what are the IDE applications you used for the development?
Netbeans, Dreamweaver

2. Have you used source control tools in your development? what are the tools?
Concurrent Versions System

3. The benefits of source control
Easier backups of one, central location
Easy development of new features
Historical overview of changes
Access control for revisions
Conflict resolution of competing changes

4. Concepts of source control

The repository contains all files under source control.

Source control software keeps track of the files under its control, allowing the comparison of changes over time (like this wiki’s History feature), and by whom these changes were done.

Working Copy
Every developer creates a working copy to do is work: A local copy of the repository, on which the developer works, without interfering with somebody else’s work.

Source control software allows the use of branches: copies of the main revision, in which development can be done without compromising the main revision. These changes can be merged into the main revision.

Merging allows re-introducing changes done in a branch back to the main copy (or other branches) at a later date.

IV – Json – jQuery – xml

Explain Json with php?

Json is too much easy with php There is no installation needed to use these functions; they are part of the PHP core. nothing more need to know just only use { ,[ and create json format string and use three php function json_encode() to get JSON representation of a value, json_decode() for Decodes a JSON string, ¦json_last_error() to get the last error occurred in process.

Why Use JSON over XML?

• Lighter and faster than XML as on-the-wire data format
• JSON objects are typed while XML data is typeless
> JSON types: string, number, array, boolean,
> XML data are all string
• Native data form for JavaScript code
> Data is readily accessible as JSON objects in your JavaScript
code vs. XML data needed to be parsed and assigned to variables through tedious DOM APIs
> Retrieving values is as easy as reading from an object property in your JavaScript code

1. What is jQuery ?

It’s very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2. What the use of $ symbol in Jquery?

$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

3. what

IV – Zend Framework


1. About Zend Framework?

Extending the art & spirit of PHP, Zend Framework is based on simplicity, object-oriented best practices, corporate friendly licensing, and a rigorously tested agile codebase. Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and cataloguers like StrikeIron and ProgrammableWeb.

2. Which version of PHP does Zend Framework require?

Zend Framework requires PHP 5.2.4 and up. Some Zend Framework components may work with earlier versions of PHP, but these components are tested and supported only on 5.2.4 and up. See the requirements appendix for more information.

3. Does Zend Framework support PHP 4?

No. Zend Framework was built to use all of the sophisticated object oriented features of PHP 5 and take advantage of significant performance and security enhancements.

Another consideration was support of the platform ZF would be running on. The PHP community officially discontinued support for PHP 4 as of 2008-01-01, and no critical security updates will be published for PHP 4 after 2008-08-08.

These factors, among others, convinced us that PHP 5 was the best platform for Zend Framework and applications built on ZF.

4. Where is the model in ZF’s MVC implementation?

The model component can vary dramatically in responsibilities and data store from one MVC application to the next. The ZF community has not defined a model interface, class, or other formalism simply because we wanted to avoid introducing limitations without significant added value.

5. Where’s the model?

Unlike the view and the controller components, the model component can vary dramatically in responsibilities and data storage from one MVC application to the next. It should represent what your application does in the abstract. The Zend Framework community has not defined a model interface, class, or other formalism because we haven’t identified enough added value to justify limitations on what constitutes a model.

What is autoloader?
Autoloader is function that load all the object on start up.

What is use of Zend front controller?
Routing and dispatching is managed in the front controller. It collects all the request from the server and handles it.

How to call two different views from same action?
Public function indexAction() {

Public function indexAction() {
Now in your index.phtml you can have this statement to call other view
$this->action(‘action name’,’controller name’,’module name’,array(‘parameter name’=>’parameter value’));

Can we call a model in view?
Yes, you can call a model in view. Simple create the object and call the method.
$modelObj = new Application_Model_User();

What is Zend_Form?

It is mainly used to display the form. but along with this we use for filter, validation and formating our form. It have following elements
Element filter
Element validation
Element ordering.
Sub form
Rendering form elments in single call or one by one for elements.

What is Zend registry?
It is container for object and values in applications, when you set an object in zend_registry you can access in whole site.

What is zend helpers?
It can be divided in two parts,
a) Action Helper: the helper is created for controller
b) View Helper: the helper is created for view files (.phtml).

What do you know about zend layout.
It work as a site template and have following features.
Automatic selection and rendering layout
Provide separate scope for calling element i.e parital, render, partialLoop

What is Inflection?
It is class in zend used to modify the string like convert to lowercase, change to url by removing special chars and convert underscore to hyphen.

What is Front Controller?
It used Front Controller pattern. zend also use singleton pattern.

routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
routeShutdown: This function is called after the router finishes routing the request.
dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
preDispatch: called before an action is dispatched by the dispatcher.
postDispatch: is called after an action is dispatched by the dispatcher.

What is Zend_filter?
Zend_filter is used to filter the data as remove the tags, trailing the spaces, remove all except digits.

How to include view helper in your application?

class Application_View_Helper_Arun extends Zend_View_Helper_Abstract
function __construct() {
echo “File Path: \application\modules\default\views\helpers”;

either in application.ini
resources.view.helperPath.Application_View_Helper = APPLICATION_PATH “/modules/default/views/helpers”

OR in bootstrap.php
$view->addHelperPath(APPLICATION_PATH .DIRECTORY_SEPARATOR. ‘modules’.DIRECTORY_SEPARATOR.’default’.DIRECTORY_SEPARATOR.’views’.DIRECTORY_SEPARATOR.’helpers’, “Application_View_Helper”);


Other Links:



IV – Codeigniter


1. what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful.

Advantages :
Consistent Programming Model Direct Support for Security Simplified Development Efforts
Easy Application Deployment and Maintenance

IV – Mysql


1) What are the different Engines present in MySQL, which one is default?

Following tables (Storage Engine) we can create,

1. MyISAM (The default storage engine IN MYSQL. Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )

2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)

3. Merge

4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )

5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions)


7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )

8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )

9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)

10. BLACKHOLE (The BLACKHOLE storage engine acts as a “black hole” that accepts data but throws it away and does not store it. Retrievals always return an empty result)

2) Difference b/w MyISAM and InnoDB in MySQL?

1. The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
2. InnoDB supports some newer features: Transactions, row-level locking, foreign keys
3. InnoDB is for high volume, high performance
4. use MyISAM if they need speed and InnoDB for data integrity.
5. InnoDB has been designed for maximum performance when processing large data volumes
6. Even though MyISAM is faster than InnoDB
7. InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you issue a command it’s done
8. MyISAM does not support foreign keys where as InnoDB supports
9. Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any size even on operating systems where file size is limited to 2GB.

3) What is SQL Injection?

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

Injection Prevention – mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.

What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(‘) a user might enter with a MySQL-safe substitute, an escaped quote \’.

2. What are Aggregate and Scalar Functions?
Aggregate and Scalar functions are in built function for counting and calculations.

Aggregate functions operate against a group of values but returns only one value.
AVG(column) :- Returns the average value of a column
COUNT(column) :- Returns the number of rows (without a NULL value) of a column
COUNT(*) :- Returns the number of selected rows
MAX(column) :- Returns the highest value of a column
MIN(column) :- Returns the lowest value of a column

Scalar functions operate against a single value and return value on basis of the single value.
UCASE(c) :- Converts a field to upper case
LCASE(c) :- Converts a field to lower case
MID(c,start[,end]) :- Extract characters from a text field
LEN(c) :- Returns the length of a text

3. Query writing

Product table contains columns -> id {product id}, name {product name}, category_id {category id}
Category table contains columns -> id {category id}, name {category name}

4. MySQL GROUP_CONCAT() function (with book and category tables)

5. How to connect to my MySQL Database server using command line

You can connect to MySQL database server using mysql command line client or using programming language such as PHP or perl.
Genral syntax is as follows:

5. Mysql Indexing and the advantages

Indexing is one of the more useful features of MySQL. MySQL allows several types of indexes like primary key index, unique index, normal index also known as (“non-unique index”, ordinary index, index without constraints”) and full-text index. Of course, the indexes improve SELECT queries speed tremendously. but, they do have some considerable disadvantages as well. Advantages of MySQL Indexes

Generally speaking, MySQL indexing into database gives you three advantages:

* Query optimization: Indexes make search queries much faster.
* Uniqueness: Indexes like primary key index and unique index help to avoid duplicate row data.
* Text searching: Full-text indexes in MySQL version 3.23.23, users have the opportunity to optimize searching against even large amounts of text located in any field indexed as such.

6. Disadvantages of MySQL indexes

When an index is created on the column(s), MySQL also creates a separate file that is sorted, and contains only the field(s) you’re interested in sorting on.

Firstly, the indexes take up disk space. Usually the space usage isn’t significant, but because of creating index on every column in every possible combination, the index file would grow much more quickly than the data file. In the case when a table is of large table size, the index file could reach the operating system’s maximum file size.

Secondly, the indexes slow down the speed of writing queries, such as INSERT, UPDATE and DELETE. Because MySQL has to internally maintain the “pointers” to the inserted rows in the actual data file, so there is a performance price to pay in case of above said writing queries because every time a record is changed, the indexes must be updated. However, you may be able to write your queries in such a way that do not cause the very noticeable performance degradation.

7. What are E-R diagrams?

E-R diagram also termed as Entity-Relationship diagram shows relationship between various tables in the database.

8. How many types of relationship exist in database designing?

There are three major relationship models:-

1) One-to-one
2) One-to-many
3) Many-to-many

9. What is the SQL ” IN ” clause?

SQL IN operator is used to see if the value exists in a group of values.
For instance the below SQL checks if the Name is either ‘rohit’ or ‘Anuradha’ SELECT * FROM pcdsEmployee WHERE name IN (‘Rohit’,’Anuradha’)

Also you can specify a not clause with the same.

SELECT * FROM pcdsEmployee WHERE age NOT IN (17,16);

10. What is a self-join?

If we want to join two instances of the same table we can use self-join.

11. What’s the difference between DELETE and TRUNCATE ?

Following are difference between them:

DELETE TABLE syntax logs the deletes thus making the delete operations low.
TRUNCATE table does not log any information but it logs information about deallocation of data page of the table. So TRUNCATE table is faster as compared to delete table.

DELETE table can have criteria while TRUNCATE can not.

TRUNCATE table can not have triggers.

12. What’s the difference between “UNION” and “UNION ALL”?

UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the table.

UNION ALL selects all records from both the tables.

13. What is the difference between “HAVING” and “WHERE” clause?

HAVING clause is used to specify filtering criteria for “GROUP BY”
WHERE clause applies on normal SQL

14. What is a View?

View is a virtual table which is created on the basis of the result set returned by the select statement.

CREATE VIEW [MyView] AS SELECT * from pcdsEmployee where LastName = ‘singh’

In order to query the view

15. In how many ways we can retrieve the data in the result set of MySQL using PHP? What is the difference between mysql_fetch_object and mysql_fetch_array ?

we can retrieve the data in the result set of MySQL using PHP in 4 Ways

1. mysqli_fetch_row >> Get a result row as an enumerated array
2. mysqli_fetch_array >> Fetch a result row as associative and numeric array
3.mysqli_fetch_object >> Returns the current row of a result set as an object
4. mysqli_fetch_assoc >> Fetch a result row as an associative array

mysqli_fetch_object() is similar to mysqli_fetch_array(), with one difference – an object is returned, instead of an array.

Indirectly, that means that, we can only access the data by the field names, and not by their offsets (numbers are illegal property names).


1) Difference between php4 and php5?

PHP5 introduces many new features, I have mentioned some of them:

Unified Constructors and Destructors:
In PHP4, constructors had same name as the class name. In PHP5, you have to name your constructors as __construct() and destructors as __destruct().

In PHP5 you can declare a class as Abstract.

Startic Methods and properties:
Static methods and properties are also available. When you declare a class member as static, then you can access members using :: operator without creating an instance of class.

PHP5 introduces a special function called __autoload()

PHP5 allows you to declare a class or method as Final

Magic Methods
PHP5 introduces a number of magic methods. __call, __get, __set and __toString

In PHP5, There are 3 levels of visibilities:
Public: Methods are accessible to everyone including objects outside the classes.
Private: only available to the class itself.
Protected: accessible to the class itself and inherited class.

PHP5 has introduced ‘exceptions’(exception errors)

Passed by reference
In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference.

PHP5 introduces interfaces . An interface defines the methods a class must implement. All the methods defined in an interface must be public.

E_STRICT Error Level
PHP5 introduces new error level defined as ‘E_STRICT’. E_STRICT will notify you when you use depreciated code.

3. What are the features and advantages of object-oriented programming?

OOP has following features:
- Modifiers to control access to properties and methods (essential for encapsulation)
- A unified constructor name, __construct()
- Support for explicitly cleaning up resources through a destructor function
- Support for interfaces and abstract classes
- Final classes
- Static classes, properties, and methods
- Automatic class loading

The approach taken by OOP has two distinct advantages, namely:

- Code reusability:

Breaking down complex tasks into generic modules makes it much easier to reuse code. Class files are normally separate from the main script, so they can be quickly deployed in different projects.

- Easier maintenance and reliability:

Concentrating on generic tasks means each method defined in a class normally handles a single task. This makes it easier to identify and eliminate errors. The modular nature of code stored outside the main script means that, if a problem does arise, you fix it in just one place. Once a class has been thoroughly tried and tested, you can treat it like a black box, and rely on it to produce consistent results.

2) Explain about inheritance in OOPS?

Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

3) Explain about a class in OOP?

In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

4) Explain the usage of encapsulation?

Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

5) Explain about abstraction?

Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.

6) Explain what a method is?

A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.

7) Explain about polymorphism?

Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.

8) What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract.
That means all the methods only declared but not defined. All the methods must be define by its implemented class.

9) what are magic methods?
Magic methods are the members functions that is available to all the instance of class.

Magic methods always starts with “__”. Eg. __construct

All magic methods needs to be declared as public
To use magic method they should be defined within the class or program scope

Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()

10) Types of error? How to set error settings at run time?

Here are three basic types of runtime errors in PHP:

1. Notices:
These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behaviour.

2. Warnings:
These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors:
These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script.

IV – PHP – Bascis


1) how to increase the web page performance ?

Use lightweight templates
Put Stylesheets at the Top
Put Scripts at the Bottom
Avoid CSS Expressions like As an example, the background color could be set to alternate every hour using CSS expressions.
background-color: expression( (new Date()).getHours()%2 ? “#B8D4FF” : “#F08A00″ );
Make JavaScript and CSS External
Minify JavaScript and CSS : Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times.
Remove Duplicate Scripts
Choose over @import
Don’t Scale Images in HTML
Make favicon.ico Small and Cacheable
use Ajax, JSON, Jquery for fastening results

2. How to get the http Request in PHP?

When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:

$_GET – Associate array of variables submitted with GET method.
$_POST – Associate array of variables submitted with POST method.
$_COOKIE – Associate array of variables submitted as cookies.
$_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.
$_SERVER – Associate array of all information from the server and the HTTP request.

3. How you provide security for PHP application?

There are many ways to accomplish the security tasks but the most common 7 ways are

1. Validate Input. Never trust your user and always filter input before taking it to any operation.
2. Provide access control.
3. Session ID protection
4. preventing Cross Site Scripting (XSS) flaws
5. SQL injection vulnerabilities.
6. Turning off error reporting and exposing to the site for hackers. Instead use log file to catch exceptions
7. Effective Data handling

4. PHP how to know user has read the email?

Using Disposition-Notification-To: in mailheader we can get read receipt.
Add the possibility to define a read receipt when sending an email.
It’s quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at ‘createHeader’ function add:
if (!empty($this->readReceipt))
$this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine;

5. What are the differences between GET and POST methods in form submitting?

On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.

On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.

GET method is mostly used for submitting a small amount and less sensitive data.
POST method is mostly used for submitting a large amount or sensitive data.

6. What Is a Session?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

5. What is the mean of Regular Expressions ? What the use of Regular Expressions ?

Regular Expressions means we can say a pattern that one is an expression that specifies a set of strings.
And there are lot of great use of these expressions like

In complex search
In validation like email validation or URl validation etc
in writing of rewrite rules in apache or .htaccess file
in file search in linux
in pattern matches

6. Explaind about header funciton in php and its uses?

1) The http header allows you to send many messages to the browser, the first of these that I’ll explain is the location header.

2) This will send a new location to the browser and it will immediately redirect. It’s recommended to put a full url there, however almost all browsers support relative urls.

You can also control the content type that the browser will treat the document as:

3) You can now link to this file as css.php in your link to your css and dynamically create your css document depending on what browser or resolution the viewer has. This can be really helpful when designing css that works in every browser.

You can also force the browser to display the download prompt and have a recommended filename for the download.

4) This will not show the file as it usually would in a browser, but as I mentioned before, display the downloads prompt and the filename will automatically be set to file.jpg regardless the filename of the php file. You can also force the page to be displayed inline by changing the content-disposition from attachment to inline.

You can also send specific errors to the browser using the header function. It’s important to remember the different error messages and what they mean.

5) Finally, I’d like to suggest that immediately following using a header, you use exit to make sure none of the code after it is executed (unless of course that code is used to make an image or needed in the file):

7. Is variable name casesensitive ? could we start a variale with number like $4name ? What is the difference between $name and $$name?

Yes, variable name is case sensitive and we can not start a variable with number like $4name as A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

where as $$ is variable of variable $name is variable where as $$name is variable of variable

like $name=sonia and $$name=singh so $sonia value is singh.

8. What is htaccess? Why do we use this and Where?

.htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis.

A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

9. What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system.
unset() makes a variable undefined.

10. What is garbage collection? default time ? refresh time?

Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them.

Garbage Collection process only runs in the default session save directory, which is /tmp.

If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it.

the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.

There are 3 php.ini variables, which deal with the garbage collector:

variable name and its default values

session.gc_maxlifetime 1440 seconds or 24 minutes
session.gc_probability 1
session.gc_divisor 100

11. what is session_set_save_handler in PHP?

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

12. What are the types of cookies?

There are two different types of cookies:

Session cookies – these are temporary and are erased when you close your browser at the end of your surfing session. The next time you visit that particular site it will not recognise you and will treat you as a completely new visitor as there is nothing in your browser to let the site know that you have visited before (more on session cookies).

Persistent cookies – these remain on your hard drive until you erase them or they expire. How long a cookie remains on your browser depends on how long the visited website has programmed the cookie to last (more on persistent cookies).

12. persistent cookie in php?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer.

Content of a Persistent cookie remains unchanged even when the browser is closed.
Persistent cookies are less secure because users can open cookie files see the cookie values.
Persistent cookies can be used for tracking long-term information.

Setting cookie in php:
Cookies in PHP can be set using the setcookie() function

Setcookie(name, value, expire, path, domain);


13. Difference b/w echo and print in php?

1. echo can take more than one parameter when used without parentheses.
2. echo does not return any value
3. In PHP, echo is not a function but a language construct.
4. syntax: void echo ( string $arg1 [, string $... ] );

1. print only takes one parameter.
2. print always returns 1 (integer)
3. In PHP, print is not a really function but a language construct. However, it behaves like a function in that it returns a value.
4. syntax: int print ( string $arg )

14. Difference between Cookies and Session in PHP

Cookies are stored in the user’s browser memory. A cookie can keep information in the user’s browser until deleted.
Session : logical object that allows you to preserve data across subsequent http requests.Whenever PHP creates a new session, it generates a session ID.

Session values are store in server side not in user’s machine. A session is available as long as the browser is opened. User couldn’t be disabled the session.

Cookies are stored in client side and sessions are stored in server side.

Cookies can only store strings.
We could store not only strings but also objects in session.

we could be save cookie for future reference, but session couldn’t. When users close their browser, they also lost the session.

* Regular Expressions interview questions

Top Regular Expressions interview questions and answers

Questions : 1 What is the mean of Regular Expressions ? What the use of Regular Expressions ?
Answers : 1 Regular Expressions means we can say a pattern that one is an expression thatspecifies a set of strings. And there are lot of great use of these expressions like

  • In complex search
  • In validation like email validation or URl validation etc
  • in writing of rewrite rules in apache or .htaccess file
  • in file search in linux
  • in pattern matches
Questions : 2 What the mean of different symbols like ^, $, * , + , ?, ., {},[]in Regular Expressions
Answers : 2 These symbols ^, $, * , + , ?, ., {},[] are very usefull like

  • “^PCDS”: Symbols ^ use to matches any string that starts with “PCDS”this can match “PCDS is an Infotech”;
  • “pcds$”: Matches a string that ends in the substring “pcds”like “This is pcds”;
  • “^pcds$”: Matches a string that starts and ends with “pcds”that could only be “pcds” itself
  • “ab*”: matches a string that has an a followed by zero or more b’s (“a”, “ab”, “abbb”, etc.);
  • “ab+”: same as *, but there’s at least one b (“ab”, “abbb”, etc.);
  • “ab?”: there might be a b or not;
  • “ab.”: . matches any character like abd, abh, abt etc;
  • “ab{2}”: matches a string that has an a followedby exactly two b’s (“abb”);
  • “ab{2,}”: there are at least two b’s (“abb”, “abbbb”, etc.);
  • “ab{3,5}”: from three to five b’s (“abbb”, “abbbb”, or “abbbbb”).
  • “[a-z]“: matches any char from a to z.
Questions : 3 How we list which characters we DON’T want ?How to use backslash character
Answer : 3 We can list which characters we DON’T want so just use a ‘^’ as the first symbol in a bracket expression(i.e., “%[^a-zA-Z]%” matches a string with a character that is not a letter between two percent signs).

“^[a-zA-Z]“: a string that starts with a letter;

“[0-9]%”: a string that has a single digit before a percent sign;

“,[a-zA-Z0-9]$”: a string that ends in a comma followed by an alphanumeric character.In order to be taken literally, you must escape the characters “^.[$()|*+?{\" with a backslash ('\'), as they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression "(\$|¥)[0-9]+” would have the function call: ereg(“(\\$|¥)[0-9]+”, $str)

Questions : 4 How you can validate email id use REG expression
Answer : 4 By using below reg expression we can validate email id^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$“^[_a-z0-9-]+”: start with any underscore or alphanumeric one or more then one alfanumaric word

“(\.[_a-z0-9-]+)*@”:any dot(.) or alphanumeric zero times or more the zero and a @ sign

“[a-z0-9-]+”:one or more alphanumeric

“(\.[a-z0-9-]+)*”: zero or more dot alphanumeric or -(mins sign)

“(\.[a-z]{2,5})$”: End with two to 5 character may use dot (.) in that

* Php Objective Questions with Answers

Php Objective Questions with Answers for written test exams all

Question 1

What will the following script output?


$x = 3 – 5 % 3;

echo $x;


A. 2

B. 1

C. Null

D. True

E. 3

Answers 1

Answer B is correct. Because of operator precedence, the modulus operation is

performed first, yielding a result of 2 (the remainder of the division of 5 by 2).

Then, the result of this operation is subtracted from the integer 3.

Question 2

Which data type will the $a variable have at the end of the following script?


$a = “1”;

echo $x;


A. (int) 1

B. (string) “1”

C. (bool) True

D. (float) 1.0

E. (float) 1

Answers 2

Answer B is correct.When a numeric string is assigned to a variable, it remains

a string, and it is not converted until needed because of an operation that

requires so.

Question 3

What will the following script output?


$a = 1;

$a = $a— + 1;

echo $a;


A. 2

B. 1

C. 3

D. 0

E. Null

Answers 3

Answer A is correct.The expression $a— will be evaluated after the expression $a

= $a + 1 but before the assignment.Therefore, by the time $a + 1 is assigned to

$a, the increment will simply be lost.

Question 4

What will the following script output?


class a


var $c;

function a ($pass)


$this->c = $pass;


function print_data()


echo $this->$c;



$a = new a(10);



A. An error

B. 10

C. “10”

D. Nothing

E. A warning

Answers 4

Answer D is correct.There actually is a bug in the print_data() function—

$this->$c is interpreted as a variable by PHP, and because the $c variable is not

defined inside the function, no information will be available for printing. Note

that if error reporting had been turned on, either through a php.ini setting or

through an explicit call to error_reporting(), two warnings would have been

outputted instead—but, unless the exam question tells you otherwise, you should

assume that the normal PHP configuration is being used. And in that case, the

interpreter is set not to report warnings.

Question 5

When serializing and unserializing an object, which of the following precautions

should you keep in mind? (Choose two)

A. Always escape member properties that contain user input.

B. If the object contains resource variables, use magic functions to restore the

resources upon unserialization.

C. Use the magic functions to only save what is necessary.

D. Always use a transaction when saving the information to a database.

E. If the object contains resource variables, it cannot be serialized without first

destroying and releasing its resources.

Answers 5

Answers B and C are correct.Whenever you design an object that is meant to be

serialized or that can contain resource objects, you should implement the appropriate

magic functions to ensure that it is serialized and unserialized properly—and

using the smallest amount of information possible.

Question 6

What will the following script output?



class a


var $c;

function a()


$this->c = 10;



class b extends a


function print_a()


echo $this->c;



$b = new b;



A. Nothing

B. An error because b does not have a constructor

C. 10


E. False

Answers 6

Answer C is correct. Because the class b does not have a constructor, the constructor

of its parent class is executed instead.This results in the value 10 being assigned

to the $c member property

Question 7

Is it possible to pass data from PHP to JavaScript?

A. No, because PHP is server-side, and JavaScript is client-side.

B. No, because PHP is a loosely typed language.

C. Yes, because JavaScript executes before PHP.

D. Yes, because PHP can generate valid JavaScript

Answers 7

Answer D is correct. JavaScript, like HTML, can be dynamically generated by

PHP. Answers A and B are incorrect because the answer is yes. Answer C is incorrect

because PHP executes before JavaScript.

Question 8

Is it possible to pass data from JavaScript to PHP?

A. Yes, but not without sending another HTTP request.

B. Yes, because PHP executes before JavaScript.

C. No, because JavaScript is server-side, and PHP is client-side.

D. No, because JavaScript executes before PHP.

Answers 8

Answer A is correct. Although your instincts might lead you to believe that you

cannot pass data from JavaScript to PHP, such a thing can be achieved with another

HTTP request. Answer B is incorrect because PHP executing before JavaScript

is not what makes this possible.This is actually the characteristic that might lead

you to believe (incorrectly) that the answer is no. Answers C and D are incorrect

because the answer is yes, but also because the explanations given are false.

Question 9

Which types of form elements can be excluded from the HTTP request?

A. text, radio, and check box

B. text, submit, and hidden

C. submit and hidden

D. radio and check box

Answers 9

Answer D is correct.When not selected, both radio buttons and check boxes are

excluded from the HTTP request. Answer A and B are incorrect because text

boxes are always included in the request. Answer C is incorrect because hidden

form elements are always included.

Question 10

When processing the form, what is the difference between a hidden form element

and a nonhidden one, such as a text box?

A. The hidden form element does not have a name.

B. There is no difference.

C. The hidden form element does not have a value.

D. The hidden form element is excluded from the request.

Answers 10

Answer B is correct.When processing a form, each form element is simply a

name/value pair within one of the superglobal arrays. Answers A and C are incorrect

because hidden form elements can (and should) have both a name and a

value. Answer D is incorrect because hidden form elements are only excluded

from the user’s view, not from the HTTP request.

Question 11

Which of the following form element names can be used to create an array in


A. foo

B. [foo]

C. foo[]

D. foo[bar]

Answers 11

Answer C is correct. PHP will create an enumerated array called foo that contains

the values of all form elements named foo[] in the HTML form.Answers A, B,

and D are incorrect because any subsequent form elements of the same name will

overwrite the value in previous elements.

Question 12

When an expiration date is given in a Set-Cookie header, what is the resulting

behavior in subsequent requests?

A. If the expiration date has expired, the cookie is not included.

B. The behavior is the same; the expiration date is included in the Cookie

header, and you can access this information in the $_COOKIE superglobal


C. The cookie persists in memory until the browser is closed.

D. The cookie is deleted and therefore not included in subsequent requests.

Answers 12

Answer A is correct. Answer B is incorrect because only the name and value of the

cookie are included in the Cookie header. Answer C is incorrect because setting

an expiration date causes a cookie to either be deleted (if the date has expired) or

written to disk. Answer D is incorrect because the cookie is only deleted if the

date has expired, which isn’t necessarily the case.

Question 13

If you set a cookie with either setcookie() or header(), you can immediately

check to see whether the client accepted it.

A. True, you can check the $_COOKIE superglobal array to see if it contains the

value you set.

B. True, but only if register_globals is enabled.

C. False, you can only use setcookie() if you need to test for acceptance.

Using header() does not work.

D. False, you must wait until you receive another HTTP request to determine

whether it includes the Cookie header.

Answers 13

Answer D is correct.The response that contains the Set-Cookie header is not sent

until PHP finishes executing, so you cannot test for acceptance prior to this.

Answers A and B are incorrect because the answer is false. Answer C is incorrect

because using setcookie() and header() both result in the same thing: A Set-

Cookie header is included in the response.

Question 14

Why must you call session_start() prior to any output?

A. Because it is easy to forget if not placed at the top of your scripts.

B. Because you can no longer access the session data store after there has been


C. Because session_start() sets some HTTP headers.

D. Because calling session_start() causes the HTTP headers to be sent.

Answers 14

Answer C is correct. Answer A is incorrect because this is a technical necessity, not

a best practice. Answer B is incorrect because accessing the session data store is

completely independent of whether there has been any output. Answer D is incorrect

because you can set other HTTP headers after a call to session_start().

Question 15

Which of the following represents the proper way to set a session variable?

A. $_SESSION[‘foo’] = ‘bar’;

B. session_start();

C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,

‘mywrite’, ‘mydelete’, ‘mygarbage’);

D. $foo = $_SESSION[‘foo’];

Answers 15

Answer A is correct. Answer B is incorrect because session_start() only activates

PHP sessions for the current script. Answer C is incorrect because

session_set_save_handler() allows you to override PHP’s default session

mechanism with your own custom functions. Answer D is incorrect; session data is

being used as the value of a regular variable and is not being manipulated in any


Question 16

Which of the following functions allows you to store session data in a database?

A. session_start();

B. session_set_save_handler();

C. mysql_query();

D. You cannot store session data in a database.

Answers 16

Answer B is correct.You can use session_set_save_handler() to override

PHP’s default session-handling functions and store session data any way you want.

Answer A is incorrect because session_start() only activates PHP sessions for

the current script. Answer C is incorrect because mysql_query() only executes a

query with MySQL and does not affect the behavior of PHP’s session mechanism.

Answer D is incorrect because this statement is false

Question 17

Which of the following types can be used as an array key? (Select three.)

A. Integer

B. Floating-point

C. Array

D. Object

E. Boolean

Answers 17

Answers A, B, and E are correct. A Boolean value will be converted to either 0 if

it is false or 1 if it is true, whereas a floating-point value will be truncated to its

integer equivalent.Arrays and objects, however, cannot be used under any circumstance.

Question 18

Which of the following functions can be used to sort an array by its keys in

descending order?

A. sort

B. rsort

C. ksort

D. krsort

E. reverse_sort

Answers 18

Answer D is correct.The sort() and rsort() functions operate on values, whereas

ksort() sorts in ascending order and reverse_sort() is not a PHP function.

Question 19

What will the following script output?


$a = array (‘a’ => 20, 1 => 36, 40);

array_rand ($a);

echo $a[0];


A. A random value from $a

B. ‘a’

C. 20

D. 36

E. Nothing

Answers 19

ANSWER E Only E is correct.The $a array doesn’t have any element with a numeric key of

zero, and the array_rand() function does not change the keys of the array’s elements—

only their order.

Question 20


$email = ‘bob@example.com’;

which code block will output example.com?

A. print substr($email, -1 * strrpos($email, ‘@’));

B. print substr($email, strrpos($email, ‘@’));

C. print substr($email, strpos($email, ‘@’) + 1);

D. print strstr($email, ‘@’);

Answers 20

Answer C is correct. strpos() identifies the position of the @ character in the

string.To capture only the domain part of the address, you must advance one place

to the first character after the @.

Question 21

Which question will replace markup such as img=/smiley.png with <img


A. print preg_replace(‘/img=(\w+)/’, ‘<img src=”\1”>’, $text);

B. print preg_replace(‘/img=(\S+)/’, ‘<img src=”\1”>’, $text);

C. print preg_replace(‘/img=(\s+)/’, ‘<img src=”\1”>’, $text);

D. print preg_replace(‘/img=(\w)+/’, ‘<img src=”\1”>’, $text);

Answers 21

Answer B is correct.The characters / and . are not matched by \w (which only

matches alphanumerics and underscores), or by \s (which only matches whitespace).

Question 22

Which of the following functions is most efficient for substituting fixed patterns in


A. preg_replace()

B. str_replace()

C. str_ireplace()

D. substr_replace()

Answers 22

Answer B is correct.The PHP efficiency mantra is “do no more work than necessary.”

Both str_ireplace() and preg_replace() have more expensive (and flexible)

matching logic, so you should only use them when your problem requires it.

substr_replace() requires you to know the offsets and lengths of the substrings

you want to replace, and is not sufficient to handle the task at hand.

Question 23


$time = ‘Monday at 12:33 PM’;


$time = ‘Friday the 12th at 2:07 AM’;

which code fragment outputs the hour (12 or 2, respectively)?

A. preg_match(‘/\S(\d+):/’, $time, $matches);

print $matches[1];

B. preg_match(‘/(\w+)\Sat\S(\d+):\d+/’, $time, $matches);

print $matches[2];

C. preg_match(‘/\s([a-zA-Z]+)\s(\w+)\s(\d+):\d+/’, $time,


print $matches[3];

D. preg_match(‘/\s(\d+)/’, $time, $matches);

print $matches[1];

E. preg_match(‘/\w+\s(\d+):\d+/’, $time, $matches);

print $matches[1];

Answers 23

Answer E is correct. Answer A and B both fail because \S matches nonwhitespace

characters, which break the match. Answer C will correctly match the first $time

correctly, but fail on the second because ‘12th’ will not match [a-zA-Z]. Answer D

matches the first, but will fail on the second, capturing the date (12) instead of the


Question 24

Which of the following output ‘True’?

A. if(“true”) { print “True”; }

B. $string = “true”;

if($string == 0) { print “True”; }

C. $string = “true”;

if(strncasecmp($string, “Trudeau”, 4)) { print “True”; }

D. if(strpos(“truelove”, “true”)) { print “True”; }

E. if(strstr(“truelove”, “true”)) { print “True”; }

Answers 24

Answers A, B, C, and E are correct. Answer A is correct because a non-empty

string will evaluate to true inside an if() block. Answer B is covered in the chapter—

when comparing a string and an integer with ==, PHP will convert the string

into an integer. ‘true’ converts to 0, as it has no numeric parts. In answer C,

strncasecmp() returns 1 because the first four characters of ‘Trud’ come before

the first four characters of true when sorted not case sensitively. Answer D is

incorrect because strpos() returns 0 here (true matches truelove at offset 0).

We could make this return True by requiring strpos() to be !== false. Answer

E is correct because strstr() will return the entire string, which will evaluate to

true in the if() block.

Question 25

What are the contents of output.txt after the following code snippet is run?


$str = ‘abcdefghijklmnop’;

$fp = fopen(“output.txt”, ‘w’);

for($i=0; $i< 4; $i++) {

fwrite($fp, $str, $i);



A. abcd

B. aababcabcd

C. aababc

D. aaaa

Answers 25

The correct answer is C. On the first iteration, $i is 0, so no data is written. On

the second iteration $i is 1, so a is written. On the third, ab is written, and on the

fourth abc is written.Taken together, these are aababc.

Question 26

Which of the following can be used to determine if a file is readable?

A. stat()

B. is_readable()

C. filetype()

D. fileowner()

E. finfo()

Answers 26

The correct answers are A and B. stat() returns an array of information about a

file, including who owns it and what its permission mode is.Together these are

sufficient to tell if a file is readable. is_readable(), as the name implies, returns

true if a file is readable.

Question 27

Specifying the LOCK_NB flag to flock() instructs PHP to

A. Return immediately if someone else is holding the lock.

B. Block indefinitely until the lock is available.

C. Block for a number of seconds dictated by the php.ini setting

flock.max_wait or until the lock is available.

D. Immediately take control of the lock from its current holder.

Answers 27

The correct answer is A.The LOCK_NB flag instructs PHP to take a nonblocking

lock, which immediately fails if another process holds the lock.



If you have an open file resource, you can read data from it one line at a time with

the _____ function.

Answers 28

The correct answer is fgets().

Question 29

Which of the following functions require an open file resource?

A. fgets()

B. fopen()

C. filemtime()

D. rewind()

E. reset()

Answers 29

The correct answers are A and D. fgets() and rewind() both act on an open file

resource. fopen() opens files to create resources, whereas filemtime() takes a filename

and reset() acts on arrays.

Question 30

Which of the following sentences are incorrect?

A. date() returns the current UNIX datestamp.

B. date() returns a formatted date string.

C. date() requires a time stamp to be passed to it.

D. date() returns a date array.

Answers 30

The correct answers are A, C, and D. date() takes a format string and an optional

time stamp and produces a formatted date string. If a UNIX time stamp is not

passed into date(), it will use the current time.

Question 31

The ________ function will return the current UNIX time stamp.

Answers 31

The correct answer is time().



Which of the following functions will output the current time as 11:26 pm?

A. print date(‘H:m a’);

B. print date(‘G:M a’);

C. print date(‘G:i a’);

D. print strftime(‘%I:%M %p’);

Answers 32

The correct answers are C and D.

Question 33

The PHP date functions are only guaranteed to work for dates after _____.

A. January 1, 1970 00:00:00

B. January 1, 1900 00:00:00

C. January 1, 1963 00:00:00

D. January 18, 2038 22:14:07

Answers 33

The correct answer is A.The UNIX epoch is January 1, 1970 00:00:00 UTC. On

32-bit systems, the date functions are only guaranteed to work until January 19,


Question 34

Internally PHP handles dates and times as

A. A ‘date array’ array consisting of the year, month, day, hour, minute, and


B. A UNIX time stamp representing the number of seconds since the UNIX


C. An ISO-8601 date entity.

D. A UNIX time stamp consisting of the number of microseconds since the

UNIX epoch.

Answers 34

The correct answer is B. PHP stores all its dates internally as UNIX time stamps,

which are defined as the number of seconds since the UNIX epoch, January 1,

1970 00:00:00 UTC.

Question 35

Your company sells a shopping cart written in PHP. Matching common industry

practice, the shopping cart sends a confirmational email to the user after he has

checked out.

Your team has just ported the shopping cart from PHP on Gentoo Linux to PHP

running on Windows Server 2003.They’ve correctly set the SMTP, smtp_port, and

sendmail_from settings in php.ini, but this error appears when the shopping cart

tries to send the confirmation email:

Could not execute mail delivery program ‘sendmail’

This is your team’s first project using Windows Server, and everyone’s a bit confused

as to why this error is happening.The php.ini settings work fine on Linux,

so what could be the problem?

Choose from one of the following:

A. The smtpserver service hasn’t been started.

B. sendmail_path in php.ini needs to be commented out.

C. Microsoft Exchange needs configuring to accept email from PHP.

D. PHP cannot send email when running on Windows.

Answers 35

The correct answer is B.

Question 36

Flush with the success of the shopping cart on Windows Server 2003, your company

has decided that it would be a good idea to add Solaris to the list of supported

operating systems. Because the shopping cart is already proven to work on

Linux, it should be no trouble at all to get the cart working on Solaris.

Your team goes out and buys a new Sun server. As Solaris doesn’t come with PHP,

you have to compile PHP by hand. At the same time, your network administrator

decides to un-install the Solaris version of sendmail and replace it with the company’s

standard MTA—postfix—instead. He forgets to tell you that he’s done this.

When the time comes to test your shopping cart on Solaris, there’s a problem.

When the shopping cart tries to send the confirmation email, you get this error


Call to undefined function: mail()

What can you do to fix this problem?

A. Put an @ symbol in front of your call to mail() so that PHP does not output

the error message.

B. Put sendmail back on the machine. Postfix doesn’t provide a sendmail wrapper


C. Use mb_send_mail() instead.

D. Recompile PHP—after asking your network administrator to leave the

MTA alone until the recompilation of PHP has completed

Answers 36

The correct answer is D.

Question 37

All the new customers you’re attracting on Solaris are very pleased with your

shopping cart.Your product is earning them a lot of new customers also.

However, like all customers, they want new features. Specifically, they want you to

create and attach a simple comma-separated file that users can import into products

such as Microsoft Money.This will make it easier for customers to manage

their finances. Besides, it’s a cool feature that none of your competitors have, so the

marketing department has told your boss to get it done.

At the moment, the shopping cart sends out RFC-822–compliant plain-text

emails.What do you need to change to make it send the attachment as well?

Choose from one of the following:

A. Replace your plain-text emails with MIME-encoded emails.

B. Refuse to do it. RFC-822 doesn’t allow attachments, and your company

should not be shipping products that go against Internet standards.

C. Put the CSV file on a web server, and put a link to it in the email.

D. Ditch PHP’s built-in mail() function, and use the system() command to

call sendmail directly.

Answers 37

The correct answer is A.

Question 38

A rival has just launched a new version of his shopping cart. Unlike yours—which

only sends plain-text emails—his shopping cart sends out confirmation emails that

look more like a web page.These emails look so much nicer, and he’s starting to

eat into your sales as a result. It’s a good thing his cart only runs on Windows; otherwise,

you’d have no customers left!

Something must be done, and marketing has decided that if you can’t beat them,

join them.Your long-suffering boss has been told to make your shopping cart send

out nice-looking emails too. In the best tradition of pointy-haired bosses, he’s

dumped the whole problem in your lap, and is waiting for you to tell him how

this can be done.

What could you do to make this work? Choose one or more of the following:

A. Change your emails to send text/html MIME-encoded emails.

B. It’s time to ditch mail() again and call sendmail directly.

C. Change your emails to send text/enriched MIME-encoded emails.

D. Tell your boss that this only works

on Windows because PHP on Windows

handles emails very differently.

Answers 38

The correct answers are A and C.

Question 39

During testing of your new, much nicer-looking confirmation emails, you notice

that there’s a problem.The email uses quite a few images—including the allimportant

company logo. All of these images are stored on your web server, and

the email uses standard “<img src=…>” tags to include them.The images look

great in your email client—but appear as missing images when you send the email

to your boss to show him the results of your hard work.

Your boss isn’t pleased, and neither is the marketing department, who make it very

clear that you can’t ship the code until the company logo shows up.

The good news is that it isn’t just your email.The confirmation emails sent by

your rival also have this problem. If you can figure out how to make it work, not

only will you be playing catch-up to your rival, but you’ll also be back in the lead.

This mollifies your boss, but gets you nowhere nearer to solving the problem.

What could you change to make this work? Choose one or more of the


A. sendmail is too old. Replace it with a modern MTA instead.

B. Add all the images to the email as attachments with Content-Locations,

and make your email use the attachments rather than the images on the


C. Add a piece of inline JavaScript in your email that temporarily changes the

security settings of the email client.This will enable the images to be downloaded.

D. File a bugwith the author of the email client that your boss uses. Something

must be wrong with the way it handles RFC-1896–compliant email messages.

Answers 39

The correct answer is B—and only B.

Question 40

Which of the following is not an aggregate function?






Answers 40

The correct answer is D. Group by is a grouping clause, not an aggregate function.

Question 41

In the following query, how will the resultset be sorted?

Select * from my_table order by column_a desc, column_b, column_c

A. By column_a in descending order, by column_b in descending order, and,

finally, by column_c.

B. By column_a, column_b, and column_c, all in descending order.

C. By column_a, column_b, and column_c, all in ascending order.

D. By column_a.Any rows in which column_b has the same value will then be

resorted by column_c in descending order.

E. By column_a in descending order.Any rows in which column_a has the

same value will then be ordered by column_b in ascending order.Any rows

in which both column_a and column_b have the same value will be further

sorted by column_c in ascending order.

Answers 41

E is the correct answer.The resultset of the query will, first of all, be sorted by the

value of column_a in descending order, as dictated by the DESC clause. If, after the

first sorting operation, any rows have the same value for column_a, they will be

further sorted by column_b in ascending order. If any rows have the same value for

column_a and column_b, they will be further sorted by column_c in ascending


Question 42

How is a transaction terminated so that the changes made during its course are




C. By terminating the connection without completing the transaction



Answers 42

A and C are both valid answers. A transaction is not completed when the connection

between your script and the database server is discarded, as if a ROLLBACK

TRANSACTION command has been issued.

Question 43

The company you work for writes and sells a successful content management system

(CMS). The CMS is written in PHP.

Recently, your company has acquired the assets of one of your main competitors,

including their CMS. The plan is to discontinue the rival CMS, and migrate all of

its current customer base over to your CMS. However, this isn’t going to happen

until you’ve added some of the features that your CMS is currently lacking.

The first feature that you have to add is a dead link checker. This handy little utility

runs from the command-line, and checks a list of URLs to see whether they

still work or not. Thanks to the new streams support in PHP 4.3, this should be

very easy to do.

Unfortunately, the first time you test your code, this error appears on the screen:

Warning: fopen(): URL file-access is disabled in the server configuration in

<file> on line 3

Warning: fopen(URL): failed to open stream: no suitable wrapper could be

found in <file> on line 3

What is the cause of this error? Choose from one of the following.

A. File wrappers don’t allow you to access websites. You need to use the

CURL extension for that.

B. The web server is running behind a firewall, which is preventing access out

to the Internet.C. The web server’s configuration file contains the setting

‘allow_fopen_url=Off ’, which prevents the PHP file wrappers from


D. The php.ini configuration file contains the setting ‘allow_fopen_url=Off ’,

which prevents the PHP file wrappers from working.

Answers 43

The correct answer is D.

Question 44

Now that you’ve fixed that little problem and are able to connect to remote websites

from your PHP script, you’re faced with another problem.

Your script’s job is to determine whether or not a given URL is valid. How is

your script going to do that?

Choose from one or more of the following options.

A. If the fopen() call fails, your script can assume that the remote website no

longer exists.

B. Once you have opened the file wrapper, try reading from the file. If the

read fails, then the remote web page no longer exists.

C. Check the metadata returned by opening the file, and use the HTTP status

code returned by the server to determine whether or not the remote

webpage still exists or not.

D. You can’t use PHP to reliably check whether remote URLs exist or not.

That’s why all these tools are always written in Java.

Answers 44

The correct answers are A and C.

Question 45

Decoding the status code contained in the file wrapper’s metadata is an important


Where should you look to understand what the status code means?

Choose from one or more of the following:

A. The PHP Manual. It’s well annotated, so even if the PHP developers forgot

to list the status codes, you can be sure that a helpful PHP user has added

them somewhere.

B. Microsoft.com. Internet Information Server is the web server of choice for

many companies. Open standards are a nice ideal, but in the real world if

code doesn’t work for customers, you don’t get paid.

C. W3C.org. They set the standards, and standards are important. By supporting

the open standards, you can be sure that your code will work with most

of the products out in the marketplace.

D Apache.org. The Apache web server is more popular than all the other web

servers put together. If your code works with Apache, then it supports the

market leader. And that’s an important position to be in.

Answers 45

The correct answers are B and C.


Question 46

Your boss was so impressed with your new dead link checker tool that he’s given

you responsibility for adding a larger feature to the CMS product proper.

He wants you to add file replication support.

For large websites, it can be very expensive to purchase a server powerful enough

to cope with all the traffic and associated load. It’s often much cheaper to purchase

three or four smaller web servers, with a more powerful server acting as the

admin server. New content is added to the admin server, and then pushed out to

the smaller web servers.

Although most of the content lives in a shared database, original media files (PDF

files, images,Word documents, and the like) are served directly off disk. This is

partly a performance decision, and partly because some database servers have

severe limits on their support for replicating large amounts of binary data.

You must write some code to copy files from the admin server to one or more

web servers. There are no firewalls between the servers.

How would you do this? Choose one or more of the following options.

A. Put the media files into the database, and configure the web servers to

retrieve the files from the database when they are needed.

B. Use file wrappers to write the media files out to a \\server\share network


C. Don’t use file wrappers at all. Use NFS to mount the disks from the admin

server on all the web servers, and access the files directly.

D. Use NFS to mount the disks from the web servers directly onto the admin

server. Have the admin server write to each of the NFS mounts in turn.

Answers 46

The correct answers are B and D.

Question 47

Customers are fickle things.

Just as you have your new file replication code working, one of your major customers

informs you that they have installed a firewall between the admin server

and the web servers.

This totally prevents your file replication code from working.

Helpfully, the customer does allow outgoing HTTP connections through the firewall.

You’ll need to provide an alternative script, that uploads the files to the web

servers through a HTTP connection. How are you going to do that?

Choose from one or more of the following.

A. File wrappers can’t upload files via http. You’ll have to use the CURL

extension to achieve this.

B. Just open a URL as a file and write to it. The whole point of file wrappers

is to make operations like this easy.

C. Use the stream context to tell the http file wrapper where to upload the file,

and have a script on the web servers move the file from the uploads directory

to their final destination.

D. Use the FTP file wrapper to upload files directly to their final destination.

Answers 47

The correct answer is C.

Question 48

With file replication done and dusted, your boss is confident that he’ll soon have

customers migrating across from the discontinued CMS to your product. He’ll

have no trouble making his targets for the quarter, and earning his bonus.

However, he needs one more feature porting across before he can be certain that

Answers 48

customers will start migrating.

Many sites like to keep in touch with their customers via a weekly newsletter.

Many customers only come back to the website because there was something of

interest to them in the newsletter. Being able to send newsletters—and being able

to make those newsletters look professional—is an important feature.

Your CMS doesn’t support the concept of newsletters per se. But it does support

the idea of packaging groups of files for downloading. If you could write a userdefined

file wrapper that makes a MIME email look just like a ZIP file, it would

then be very easy to add newsletter support.

Sketch out a design for a file wrapper, which would allow a PHP script to add

content, graphics, and other attachments to a MIME email.

Question 49

Which of the following data filtering methods can be described as a whitelist


A. Make sure that a username does not contain backticks or angled brackets.

B. Only allow alphanumerics and underscores in a username.

C. Pass all incoming data through strip_tags().

D. Use htmlentities() to escape potentially malicious characters.

Answers 49

Answer B is correct. Answer A is incorrect because this assumes that any username

without backticks or angled brackets is valid. Answer C is incorrect because this

only removes HTML and PHP tags, assuming everything else to be valid. Answer

D is incorrect because htmlentities() only encodes HTML entities and is not

intended to filter data at all.

Question 50

With register_globals enabled, which of the following practices is particularly


A. Initialize all variables.

B. Filter all foreign data.

C. Escape all data used in SQL statements.

D. Escape all data prior to output.

Answers 50

Answer A is correct. Answers B, C, and D are incorrect because these practices are

not dependent on whether register_globals is enabled

Question 51

What are the two most important practices to mitigate the risk of an SQL injection


A. Disabling register_globals and enabling safe_mode.

B. Enabling safe_mode and filtering any data used in the construction of the

SQL statement.

C. Filtering and escaping any data used in the construction of the SQL statement.

D. Disabling register_globals and escaping any data used in the construction

of the SQL statement.

Answers 51

Answer C is correct.With properly filtered data, escaping any metacharacters that

remain can mitigate the remaining risks. Answers A, B, and D are incorrect because

register_globals does not directly affect the risk of SQL injection, and

safe_mode is unrelated

Question 52

If $foo is anticipated to be a string, what modification made to the following

query will mitigate the risk of an SQL injection vulnerability?

$sql = “insert into mytable values ($foo)”;

A. Specify the column name in the SQL statement.

B. Remove the parentheses surrounding $foo.

C. Replace the parentheses surrounding $foo with single quotes.

D. Add single quotes around $foo

Answers 52

Answer D is correct. Answer A is incorrect because specifying the column name

does not affect the behavior of the SQL statement. Answers B and C are incorrect

because the parentheses are required.

Question 53

What is the purpose of the escapeshellcmd() function?

A. To prepare data so that it can be used as a single argument in a shell command.

B. To remove malicious characters.

C. To escape metacharacters, so that they can’t be used to execute arbitrary


D. To prevent cross-site scripting attacks

Answers 53

Answer C is correct. Answer A is incorrect because escapeshellcmd() does not

attempt to solve this problem. Answer B is incorrect because escapeshellcmd()

does not actually remove characters. Answer D is incorrect because escaping data

to protect against cross-site scripting is much different than escaping data to be

used in a shell command.

Question 54

What is the purpose of the escapeshellarg() function?

A. To prepare data so that it can be used as a single argument in a shell command.

B. To remove malicious characters.

C. To escape metacharacters, so that they can’t be used to execute arbitrary


D To remove arguments from a shell command

Answers 54

Answer A is correct. Answers B and D are incorrect because escapeshellarg()

does not remove characters. Answer C is incorrect because escapeshellarg()

does not attempt to solve this problem.

Question 55

When is cross-site scripting a heightened risk?

A. When storing data submitted by the user.

B. When displaying foreign data.

C. When executing a shell command.

D. When opening a remote URL.

Answers 55

Answer B is correct.When displaying foreign data that is not properly escaped, you

can inadvertently expose your users to significant risk. Answer A is incorrect

because storing data poses no immediate threat, even though this might result in a

cross-site scripting vulnerability later. Answers C and D are incorrect because these

activities are unrelated.

Question 56

Which of the following functions can be used to escape data such that it can be

displayed without altering the appearance of the original data?

A. htmlspecialchars()

B. addslashes()

C. escapeshellargs()

D. urlencode()

Answers 56

Answer A is correct because htmlspecialchars() will convert special characters

to HTML entities that will display correctly in any Web client. Answer B is incorrect

because addslashes() only escapes single quotes. Answer C is incorrect

because escapeshellargs() is only helpful when dealing with shell command

arguments. Answer D is incorrect because URL encoding is not interpreted by

Web clients except in the context of URLs.

Question 57

What is the purpose of the open_basedir directive?

A. To indicate the directory that include() calls will use as a base.

B. To restrict file open access to a specific directory.

C. To set the working directory.

D. To allow additional file open access than that granted by safe_mode.

Answers 57

A. To indicate the directory that include() calls will use as a base.

B. To restrict file open access to a specific directory.

C. To set the working directory.

D. To allow additional file open access than that granted by safe_mode.

Answer B is correct. Answer A is incorrect because the behavior of include() is

unchanged. Answer C is incorrect because the working directory does not depend

on open_basedir. Answer D is incorrect because open_basedir is not affected by

whether safe_mode is enabled.

Question 58

Which of the following activities can safe_mode help prevent?

A. Browsing the filesystem with a specially crafted PHP script.

B. Writing a Bash shell script to read session data.

C. Browsing the filesystem with a specially crafted Perl script.

D. Accessing another user’s database.

Answers 58

Answer A is correct because you’ll only be able to browse files that have the same

ownership as your PHP script. Answers B and C are incorrect because safe_mode

cannot affect scripts written in other languages. Answer D is incorrect because

safe_mode does not attempt to prevent database access.

Question 59

How can the following line of code be improved?

$db->query(“insert into foo values($id,$bar)”);

A. Use addslashes and sprintf to avoid security holes and make the code


B. Split the query over several lines

C. Use mysql_query() instead of $db->query()

D. Define the table fields that will be affected by the INSERT statement

E. Use mysql_query()instead of $db->query() and addslashes to avoid

security holes

Answers 59

Answers A, B, and D are correct. First of all, you need to ensure that the query is

secure; this is done by executing addslashes (or the equivalent function for your

DBMS of choice) to prevent scripting attacks. If your query is long, it’s not a bad

idea to split it over several lines to get a better overview of your code. Use

sprintf() where possible to make the code cleaner. Finally it’s always a good idea

to define the table fields that will be filled by an INSERT statement to prevent

unexpected errors if the table changes.

Question 60

You developed a big application accessed by several thousand users at the same

time. Suddenly, your web server stops responding and users are getting connection

errors.What could have happened?

A. The database server was terminated because of the unusually high amount of

database accesses.

B. The web server was misconfigured so that it ran into virtual memory usage

and consequent resource starvation because of too many child processes.

C. You didn’t optimize your code design properly.

Answers 60

Answer B is correct. Although it could be possible that the database server was

killed because of the many requests from the users, they should at least be able to

see the HTML pages from the website because the web server would still be running.

If connections are timing out, it is likely that the server ran into swap space

because of misconfiguration of the number of concurrent web server child

processes and crashed because of resource starvation.

Question 61

You are in a team of developers working on a number of different business applications.

Your project manager tells you that in two weeks another three PHP

developers will join the team and that you have to ensure that they will be ready

to dive in to the current PHP code without problems.What could you do?

A. Write proper end user documentation on how to use the web front end.

B. Write proper end user documentation and generate proper PHPDoc comments

inside the code to get an API documentation.

C. The absence of documentation will actually encourage the new developers

to delve more deeply into the code.

Answers 61

Answer B is correct—or, at least, as correct as you can get in a general situation.

The key here is that you should write proper documentation at the same time as

you’re writing your code.You could then use a tool such as PHPDocumentor to

generate a nicely formatted API documentation in HTML or PDF and make it

available to any new developers who join your team.

Question 62

Suppose that you are receiving input from the user in the form of the string

“0mydeviceid” for a field for which you only allow valid numeric values.You

want to test if this variable is equal to 0 and, if it isn’t, output an error.Which

comparison operation should you use?

A. (0 = “0mydeviceid”)

B. (0 == “0mydeviceid”)

C. (0 === “0mydeviceid”)

D. None of the above

Answers 62

Answer D is correct. Because PHP is automatically trying to convert the string

“0mydeviceid” to 0 when comparing it with the equal operator == , your condition

in answer B evaluates to true even though the user input is not a valid numeric

value.The expression in answer C, on the other hand, correctly determines that

the user input is not a valid integer—but that will always be the case because

you’re likely to always receive user input in the form of a string—so, even if that

string can be converted to an integer value, the identity test will fail.

Question 63

Which of the following strings are not valid modes for the fopen() function?

A. a+b

B. b+a

C. at

D. w

E. x+

Answers 63


Question 64

Consider the following piece of code:


$arr = array(3 => “First”, 2=>“Second“, 1=>“Third“);

list (, $result) = $arr;


After running it, the value of $result would be

A. First

B. Second

C. Third

D. This piece of code will not run, but fail with a parse error.

Answers 64


Question 65

In standard SQL-92, which of these situations do not require or cannot be handled

through the use of an aggregate SQL function? (Choose 2)

A. Calculating the sum of all the values in a column.

B. Determining the minimum value in a result set.

C. Grouping the results of a query by one or more fields.

D. Calculating the sum of all values in a column and retrieving all the values of

another column that is not part of an aggregate function or GROUP BY clause.

E. Determining the mean average of a column in a group of rows.

Answers 65


Question 66

Multidimensional arrays can be sorted using the ______ function.
Answers 66

array_multisort or array_multisort()

Question 67

When using the default session handler files for using sessions, PHP stores

session information on the harddrive of the webserver.When are those session

files cleaned up?

A. PHP will delete the associated session file when session_destroy() is

called from within a script.

B. When the function session_cleanup() is called, PHP will iterate over all

session files, and delete them if they exceeded the session timeout limit.

C. When the function session_start() is called, PHP will iterate over all

session files, and delete them if they exceeded the session timeout limit.

D. When the function session_start() is called, PHP will sometimes iterate

over all session files, and delete them if they exceeded the session timeout


E. Session files are never removed from the filesystem, you need to use an automated

script (such as a cronjob) to do this.

Answers 67


Question 68

What is the order of parameters in the mail() function?

A. subject, to address, extra headers, body

B. to address, subject, extra headers, body

C. to address, subject, body, extra headers

D. subject, to address, body, extra headers

Answers 68


Question 69

Which of the following statements are correct? (Choose 3)

A. sprintf() does not output the generated string.

B. printf(“%2s%1s“, “ab“, “c“) outputs the string abc.

C. vprintf() takes at least one parameter; the first parameter is the formatting

string and the following parameters are the arguments for the ‘%’


D. printf(“%c“, “64“) will output @ and not 6.

E. sprintf(“%3.4f“, $x) outputs more than 7 characters.

F. number_format() inserts thousands of separators and decimal points different

from (,) and (.) respectively, while printf() like functions always use

(.) as decimal point.

Answers 69

A, D, and F

Question 70

The requirement is to return true for the case in which a string $str contains

another string $substr after the first character of $str? Which of the following

will return true when string $str contains string $substr, but only after the first

character of $str?



function test($str, $substr) {

return strpos(substr($str,1), $substr) >= 0;





function test($str, $substr) {

return strrchr($str, $substr) !== false;





function test($str, $substr) {

return strpos($str, $substr) > 0;



A. I only

B. II only

C. III only

D. I and II

E. I and III

F. II and III

Answers 70


Question 71

Which of the features listed below do not exist in PHP4? (Choose 2)

A. Exceptions

B. Preprocessor instructions

C. Control structures

D. Classes and objects

E. Constants

Answers 71


Question 72

What is the output of the following code snippet?


class Vehicle {


class Car extends Vehicle {


class Ferrari extends Car {




A. string(7) “Vehicle“

B. string(3) “Car“

C. array(2) {


string(7) “vehicle“


string(3) “car“


Answers 72


Question 73

The following PHP script is designed to subtract two indexed arrays of numbers.

Which statement is correct?


$a = array(5, 2, 2, 3);

$b = array(5, 8, 1, 5);

var_dump(subArrays($a, $b));





$c = count($arr1);


($c != count($arr2))



for($i = 0;

$i < $c;



$arr1[$i] – $arr2[$i];

return $res;



A. The script is valid.

B. Assignments must be made on a single line.

C. It has too many linefeed characters between statements.

D. No, the script is missing curly braces.

E. Yes it is valid, but the script will not work as expected.

Answers 73


Question 74

What is the purpose of the escapeshellarg() function?

A. Removing malicious characters.

B. Escaping malicious characters.

C. Creating an array of arguments for a shell command.

D. Preparing data to be used as a single argument in a shell command.

E. None of the above.

Answers 74


Question 75

The _________ function can be used to determine if the contents of a string can

be interpreted as a number.

Answers 75

is_numeric or is_numeric()

Question 76

Assume $comment contains a string.Which PHP statement prints out the first 20

characters of $comment followed by three dots (.)?

A. print substr($comment, 20) . ‘…‘;

B. print substr_replace($comment, ‘…‘, 20);

C. print substr($comment, 20, strlen($comment)) . ‘…‘;

D. print substr_replace($comment, 20, ‘…‘);

Answers 76


Question 77

What is the name of the function that you should use to put uploaded files into a

permanent location on your server?

Answers 77

move_uploaded_file or move_uploaded_file

Question 78

If you have a file handle for an opened file, use the __________ function to send

all data remaining to be read from that file handle to the output buffer.

Answers 78

fpassthru or fpassthru()

Question 79

Which of the following sentences are not true? (Choose 2)

A. strpos() allows searching for a substring in another string.

B. strrpos() allows searching for a substring in another string.

C. strpos() and strrchr() return -1 if the second parameter is not a substring

of the first parameter.

D. strpos() and strrpos() can return a value that is different from an integer.

E. The second parameter to substr() is the length of the substring to extract.

F. strstr() returns false if the substring specified by its second parameter is

not found in the first parameter.

Answers 79


Question 80

Which of the following sentences are correct? (Choose 2)

A. time() + 60*60*100 returns the current date and time plus one hour.

B. time() + 24*60*60 returns the current date and time plus one day.

C. time() + 24*60*60*100 returns the current date and time plus one day

Answers 80


* Mysql interview questions

Mysql interview questions and answers are below

Questions : 1 how to do login in mysql with unix shell
Answers :1 By below method if password is pass and user name is root
# [mysql dir]/bin/mysql -h hostname -u root -p pass
Questions : 2 how you will Create a database on the mysql server with unix shell
Answers : 2 mysql> create database databasename;
Questions : 3 how to list or view all databases from the mysql server.
Answers : 3 mysql> show databases;
Questions : 4 How Switch (select or use) to a database.
Answers : 4 mysql> use databasename;
Questions : 5 How To see all the tables from a database of mysql server.
Answers : 5 mysql> show tables;
Questions : 6 How to see table’s field formats or description of table .
Answers : 6 mysql> describe tablename;
Questions : 7 How to delete a database from mysql server.
Answers : 7 mysql> drop database databasename;
Questions : 8 How we get Sum of column
Answers : 8 mysql> SELECT SUM(*) FROM [table name];
Questions : 9 How to delete a table
Answers : 9 mysql> drop table tablename;
Questions : 10 How you will Show all data from a table.
Answers : 10 mysql> SELECT * FROM tablename;
Questions : 11 How to returns the columns and column information pertaining to the designated table
Answers : 11 mysql> show columns from tablename;
Questions : 12 How to Show certain selected rows with the value "pcds"
Answers : 12 mysql> SELECT * FROM tablename WHERE fieldname = "pcds";
Questions : 13 How will Show all records containing the name "sonia" AND the phone number ’9876543210′
Answers : 13 mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number = ’9876543210′;
Questions : 14 How you will Show all records not containing the name "sonia" AND the phone number ’9876543210′ order by the phone_number field.
Answer : 14 mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number = ’9876543210′ order by phone_number;
Questions : 15 How to Show all records starting with the letters ‘sonia’ AND the phone number ’9876543210′
Answers : 15 mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = ’9876543210′;
Questions : 16 How to show all records starting with the letters ‘sonia’ AND the phone number ’9876543210′ limit to records 1 through 5.
Answers : 16 mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = ’9876543210′ limit 1,5;
Questions : 16 Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with r.
Answer : 16 mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";
Questions : 17 How you will Show unique records.
Answer : 17 mysql> SELECT DISTINCT columnname FROM tablename;
Questions : 18 how we will Show selected records sorted in an ascending (asc) or descending (desc)
Answer : 18 mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;

mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

Questions : 19 how to Return total number of rows.
Answers : 19 mysql> SELECT COUNT(*) FROM tablename;
Questions : 20 How to Join tables on common columns.
Answer : 20 mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id
Questions : 21 How to Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
Answer : 21 # mysql -u root -p

mysql> use mysql;

mysql> INSERT INTO user (Host,User,Password) VALUES(‘%’,’username’,PASSWORD(‘password’));

mysql> flush privileges;

Questions : 22 How to Change a users password from unix shell.
Answers : 22 # [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password ‘new-password’
Questions : 23 How to Change a users password from MySQL prompt. Login as root. Set the password. Update privs.
Answer : 23 # mysql -u root -p

mysql> SET PASSWORD FOR ‘user’@’hostname’ = PASSWORD(‘passwordhere’);

mysql> flush privileges;

Questions : 24 How to Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.
Answer : 24 # /etc/init.d/mysql stop
# mysqld_safe –skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User=’root’;
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Questions : 25 How to Set a root password if there is on root password.
Answer : 25 # mysqladmin -u root password newpassword
Questions : 26 How to Update a root password.
Answer : 26 # mysqladmin -u root -p oldpassword newpassword
Questions : 27 How to allow the user "sonia" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.
Answers : 27 # mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to sonia@localhost identified by ‘passwd’;
mysql> flush privileges;
Questions : 28 How to give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.
Answers : 28 # mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES (‘%’,’databasename’,’username’,’Y’,’Y’,’Y’,’Y’,’Y’,’N’);
mysql> flush privileges;
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
Questions : 29 How To update info already in a table and Delete a row(s) from a table.
Answer : 29 mysql> UPDATE [table name] SET Select_priv = ‘Y’,Insert_priv = ‘Y’,Update_priv = ‘Y’ where [field name] = ‘user’;
mysql> DELETE from [table name] where [field name] = ‘whatever’;
Questions : 30 How to Update database permissions/privilages.
Answer : 30 mysql> flush privileges;
Questions : 31 How to Delete a column and Add a new column to database
Answer : 31 mysql> alter table [table name] drop column [column name];
mysql> alter table [table name] add column [new column name] varchar (20);
Questions : 32 Change column name and Make a unique column so we get no dupes.
Answer : 32 mysql> alter table [table name] change [old column name] [new column name] varchar (50);
mysql> alter table [table name] add unique ([column name]);
Questions : 33 How to make a column bigger and Delete unique from table.
Answer : 33 mysql> alter table [table name] modify [column name] VARCHAR(3);
mysql> alter table [table name] drop index [colmn name];
Questions : 34 How to Load a CSV file into a table
Answer : 34 mysql> LOAD DATA INFILE ‘/tmp/filename.csv’ replace INTO TABLE [table name] FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’ (field1,field2,field3);
Questions : 35 How to dump all databases for backup. Backup file is sql commands to recreate all db’s.
Answer : 35 # [mysql dir]/bin/mysqldump -u root -ppassword –opt >/tmp/alldatabases.sql
Questions : 36 How to dump one database for backup.
Answer : 36 # [mysql dir]/bin/mysqldump -u username -ppassword –databases databasename >/tmp/databasename.sql
Questions : 37 How to dump a table from a database.
Answer : 37 # [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Questions : 38 Restore database (or database table) from backup.
Answer : 38 # [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Questions : 39 How to Create Table show Example
Answer : 39 mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Questions : 40 How to search second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
Answers : 40

By below query we will get second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 , 1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as compare to above query SELECT salary FROM employee where salary < (select max(salary) from employe) order by salary DESC limit 1 ;


Get every new post delivered to your Inbox.