Archive for the ‘PHP’ Category

OOPS Interview Questions & Answer

Posted: October 21, 2013 in PHP
oops
1.       What is OOPS?
OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
2.       Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.
  1. Abstraction.
  2. Encapsulation.
  3. Inheritance.
  4. Polymorphism.
3.       What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.
4.       What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.
5.       What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.
Levels are Public,Protected, Private, Internal and Protected Internal.
6.       What is Polymorphism?
Polymorphism is nothing butassigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.
7.       What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class. Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritance.
8.       What are manipulators?
Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. Examples are endl and setw.
9.       Define a constructor?
Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules forconstructor are:.
  • Constructor Name should be same asclass name.
  • Constructor must have no return type.
10.   Define Destructor?
Destructor is a method which is automatically called when the object ismade ofscope or destroyed. Destructor name is also same asclass name but with the tilde symbol before the name.
11.   What is Inline function?
Inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.
12.   What is avirtual function?
Virtual function is a member function ofclass and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.
Virtual function can be achieved in C++, and it can be achieved in C Languageby using function pointers or pointers to function.
13.   What isfriend function?
Friend function is a friend of a class that is allowed to access to Public, private or protected data in that same class. If the function is defined outside the class cannot access such information.
Friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public or protected.
14.   What is function overloading?
Function overloading is defined as a normal function, but it has the ability to perform different tasks. It allowscreation of several methods with the same name which differ from each other by type of input and output of the function.
Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);
15.   What is operator overloading?
Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function , and it has their own precedence to execute.
Example:
class complex {
double real, imag;
public:
complex(double r, double i) :
real(r), imag(i) {}
complex operator+(complex a, complex b);
complex operator*(complex a, complex b);
complex& operator=(complex a, complex b);
}
a=1.2, b=6
16.   What is an abstract class?
An abstract class is a class which cannot be instantiated. Creation of an object is not possible withabstract class , but it can be inherited. An abstract class can contain only Abstract method.
17.   What is a ternary operator?
Ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types , and it is depends on the function. Ternary operator is also called asconditional operator.
18.   What is the use of finalize method?
Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected , and it is accessible only through this class or by a derived class.
19.   What are different types of arguments?
A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function , and it should match with the parameter defined. There are two types of Arguments.
  • Call by Value – Value passed will get modified only inside the function , and it returns the same value whatever it is passed it into the function.
  • Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.
20.   What is super keyword?
Super keyword is used to invoke overridden method which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.
It also forwards a call from a constructor to a constructor in the superclass.
21.   What is method overriding?
Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.
22.   What is an interface?
An interface is a collection of abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.
23.   What is exception handling?
Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.
24.   What are tokens?
Token is recognized by a compiler and it cannot be broken down into component elements. Keywords, identifiers, constants, string literals and operators are examples of tokens.
Even punctuation characters are also considered as tokens – Brackets, Commas, Braces and Parentheses.
25.   Difference between overloading and overriding?
Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments , and it may or may not return the same value in the same class itself.
Overriding is the same method names with same arguments and return types associates with the class and its child class.
26.   Difference between class and an object?
An object is an instance of a class. Objects hold any information , but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.
Class can have sub-classes, and an object doesn’t have sub-objects.
27.   What is an abstraction?
Abstraction is a good feature of OOPS , and it shows only the necessary details to the client of an object. Means, it shows only necessary details for an object, not the inner details of an object. Example – When you want to switch On television, it not necessary to show all the functions of TV. Whatever is required to switch on TV will be showed by using abstract class.
28.   What are access modifiers?
Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers , and they are as follows:.
  •  Private.
  • Protected.
  • Public.
  • Friend.
  • Protected Friend.
29.   What is sealed modifiers?
Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members.
30.   How can we call the base method without creating an instance?
Yes, it is possible to call the base method without creating an instance. And that method should be,.
Static method.
Doing inheritance from that class.-Use Base Keyword from derived class.
31.   What is the difference between new and override?
The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.
32.   What are the various types of constructors?
There are three various types of constructors , and they are as follows:.
–          Default Constructor – With no parameters.
–          Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.
–          Copy Constructor – Which creates a new object as a copy of an existing object.
33.   What is early and late binding?
Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.
34.   What is ‘this’ pointer?
THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.
35.   What is the difference betweenstructure and a class?
Structure default access type is public , but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are exclusively used for dataand it doesn’t require strict validation , but classes are used to encapsulates and inherit data which requires strict validation.
36.   What is the default access modifier in a class?
The default access modifier of a class is Private by default.
37.   What is pure virtual function?
A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A virtual function can be declared as Pure by using the operator =0.
Example -.
Virtual void function1() // Virtual, Not pure
Virtual void function2() = 0 //Pure virtual
38.   What are all the operators that cannot be overloaded?
Following are the operators that cannot be overloaded -.
  1. Scope Resolution (:: )
  2. Member Selection (.)
  3. Member selection through a pointer to function (.*)
39.   What is dynamic or run time polymorphism?
Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name,same signature but with different implementation.
40.   Do we require parameter for constructors?
No, we do not require parameter for constructors.
41.   What is a copy constructor?
This is a special constructor for creating a new object as a copy of an existing object. There will be always only on copy constructor that can be either defined by the user or the system.
42.   What does the keyword virtual represented in the method definition?
It means, we can override the method.
43.   Whether static method can use non static members?
False.
44.   What arebase class, sub class and super class?
Base class is the most generalized class , and it is said to be a root class.
Sub class is a class that inherits from one or more base classes.
Super class is the parent class from which another class inherits.
45.   What is static and dynamic binding?
Binding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time , and it is also called as early Binding.
Dynamic binding is a binding in which name can be associated with the class during execution time , and it is also called as Late Binding.
46.   How many instances can be created for an abstract class?
Zero instances will be created for an abstract class.
47.   Which keyword can be used for overloading?
Operator keyword is used for overloading.
48.   What is the default access specifier in a class definition?
Private access specifier is used in a class definition.
49.   Which OOPS concept is used as reuse mechanism?
Inheritance is the OOPS concept that can be used as reuse mechanism.
50.   Which OOPS concept exposes only necessary information to the calling functions?
Data Hiding / Abstraction

PHP interview questions and answers

Posted: November 17, 2012 in PHP
1. What’s PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

2. How can we know the number of days between two given dates using PHP?

$date1 = date(‘Y-m-d’);
$date2 = ‘2006-07-01’;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
echo “Number of days since ‘2006-07-01’: $days”;

3. How do you define a constant?

define (“MYCONSTANT”, 100);

4. What is meant by urlencode and urldecode?

urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits.
For example:
urlencode(“10.00%”) will return “10%2E00%25”. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.

5. How To Get the Uploaded File Information in the Receiving Script?

Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName][‘name’] – The Original file name on the browser system.
$_FILES[$fieldName][‘type’] – The file type determined by the browser.
$_FILES[$fieldName][‘size’] – The Number of bytes of the file content.
$_FILES[$fieldName][‘tmp_name’] – The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName][‘error’] – The error code associated with this file upload.

6. What is the difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

7. How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b.

8. How can we send mail using JavaScript?

No. There is no way to send emails directly using JavaScript.

But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:

function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject=…”;
return true;
}

9. What is the difference between ereg_replace() and eregi_replace()?

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

10. How do I find out the number of parameters passed into function ?

func_num_args() function returns the number of parameters passed in.

11. Are objects passed by value or by reference?

Everything is passed by value.

12. What are the differences between DROP a table and TRUNCATE a table?

DROP TABLE table_name – This will delete the table and its data.
TRUNCATE TABLE table_name – This will delete the data of the table, but not the table definition.

13. How do you call a constructor for a parent class?

parent::constructor($value)

14. How can we submit a form without a submit button?

If you don’t want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link.
<a href=”javascript: document.myform.submit();”>Submit Me</a>

15. How can we extract string ‘abc.com ‘ from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with “/.*@(.*)$/” as the regular expression pattern.
For example:
preg_match(“/.*@(.*)$/”,”http://info@abc.com&#8221;,$data);
echo $data[1];

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

unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.

17. What is the difference between characters 47 and \x47?

The first one is octal 47, the second is hex 47.

18. How can we create a database using PHP and mysql?

We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

19. How can we destroy the session, how can we unset the variable of a session?

session_unregister() – Unregister a global variable from the current session
session_unset() – Free all session variables

20. How can we know the count/number of elements of an array?

a) sizeof($array) – This function is an alias of count()
b) count($urarray) – This function returns the number of elements in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1

21. How many values can the SET function of MySQL take?

MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

22. What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?

DESCRIBE table_name;

23. How can we find the number of rows in a table using MySQL?

SELECT COUNT(*) FROM table_name;

24. How can we find the number of rows in a result set using PHP?

$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;

25. What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10) column.
VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!” in VARCHAR(10) column.

26. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

mysql_fetch_array – Fetch a result row as an associative array and a numeric array.
mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

27. What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used)
htmlentities() – Convert ALL special characters to HTML entities

28. How can we get the properties (size, type, width, height) of an image using php image functions?

image size use getimagesize() function
image width use imagesx() function
image height use imagesy() function

29. How can we increase the execution time of a php script?

By the use of void set_time_limit(int seconds)

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

31. What is the maximum size of a file that can be uploaded using PHP and how can we change this?

change maximum size of a file set upload_max_filesize variable in php.ini file

32. Explain the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

33. What’s the difference between include and require?

It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

34. How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

35. What is the difference between $message and $$message?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

36. How can we get the browser properties using php?

<?php
echo $_SERVER[‘HTTP_USER_AGENT’] . “\n\n”;
$browser = get_browser(null, true);
print_r($browser);
?>

37. How can we know that a session is started or not?

A session starts by session_start()function.
this session_start() is always declared in header portion.it always declares first.then
we write session_register().

38. What is the use of obj_start()?

Its intializing the object buffer, so that the whole page will be first parsed (instead of parsing in parts and thrown to browser gradually) and stored in output buffer so that after complete page is executed, it is thrown to the browser once at a time.

39. What is the difference between Split and Explode?

split()-used for JavaScript for processing the string and the explode()-used to convert the String to Array, implode()-used for convert the array to String
Here the Example
<?php
$x=”PHP is a ServerSide Scripting Language”;
$c=explode(” “,$x);
print_r($c);
$d=implode(” “,$c);
echo ”
“.$d;
?>
Javascript Example:
list($month, $day, $year) = split(‘[/.-]’, $date);

40. Which will execute faster on php POST or GET?

Both are same while performing the action but using POST security is there.
Because using GET method in the action, form field values send along with URL, so at the time of sending password, problem will occur means password also will shown in the URL.
Using of POST there is no problem.

GET method has a limit of sending parameters 100 characters but POST method does not have a limit of sending data

GET is faster than POST. Because GET fetch the data directly from the URL but POST method fetch the encrypted data from the page.

41. What is the use of sprintf() function?

The sprintf() function writes a formatted string to a variable.

42. What Is a Session?

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

43. What is the use of header() function in php?

The header() function is used for redirect the page.if you want to redirect one page to another we can use it.

44. How can i get ip address?

REMOTE_ADDR – the IP address of the client
REMOTE_HOST – the host address of the client

45. What is htaccess?

.htaccess files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis.

46. What is the diffrence between Notify URL and Return URL?

Notify URL is used to just notify the status while processing.
Return URL is used to return after processing.

47. What is the difference between ucfirst and ucwords?

ucfirst() to convert the first letter of every string to uppercase, and ucwords(), to convert the first letter of every word in the string to uppercase.

48. What is meant by nl2br()?

nl2br() inserts a HTML tag <br> before all new line characters \n in a string.

49. How To Read the Entire File into a Single String?

<?php
$file = file_get_contents(“/windows/system32/drivers/etc/services”);
print(“Size of the file: “.strlen($file).”n”);
?>

50. What are the different functions in sorting an array?

Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()

Questions : 1 What is Full form of PHP ? Who is the father or inventor of PHP ?
Answers : 1 Rasmus Lerdorf is known as the father of PHP that started development of PHP in 1994
for their own Personal Home Page (PHP) and they released PHP/FI (Forms Interpreter) version 1.0 publicly on 8 June 1995 But in 1997 two Israeli developers named Zeev Suraski and Andi Gutmans rewrote the parser that formed the base of PHP 3 and then changed the language’s name to the PHP: Hypertext Preprocessor.
Questions : 2 What are the differences between PHP3 and PHP4 and PHP5 ? what is the current stable version of PHP ? what advance thing in php6
Answers : 2 The current stable version of PHP is PHP 5.4.6 on 2012-08-16 as still waiting for PHP6 with unicode handlig thing
There are lot of difference among PHP3 and PHP4 and PHP5 version of php so Difference mean oldest version have less functionality as compare to new one like

Questions : 3 Is variable name casesensitive ? could we start a variale with number like $4name ? What is the difference between $name and $$name?
Answer : 3 Yes variable name casesensitive 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.
Questions : 4  What is use of header() function in php ? What the Limitation of HEADER()?
Answers : 4 In PHP Important to notice the Limitation of HEADER() function is that header() must be called before any actual output is send. Means must use header function before HTML or any echo stateament
There are Number of Use of HEADER() function in php like below
1> The header() function use to sends a raw HTTP header to a client.
2> We can use herder() function for redirection of pages.
3> Use for refresh the page on given time interval automatically.
4> To send email header content like cc, bcc , reply to etc data and lot more .

Questions : 5 How can we extract string “pcds.co.in” from a string “http://info@pcds.co.in&#8221; using regular expression of PHP? More on Reg can you explain
Answers : 5 We can extract string “pcds.co.in” using this
preg_match(“/^http:\/\/.+@(.+)$/”,”http://info@pcds.co.in&#8221;,$matches);
echo $matches[1];
More On regular expression interview question with very nice examples in

Questions : 6 How do you connet mysql database with PHP ?
Answer : 6 We can connect Mysql Database with PHP using both Procedural and Object oriented style like below
$link = mysqli_connect(“localhost”, “username”, “password”, “dbofpcds”);$mysqli = new mysqli(“localhost”, “username”, “password”, “dbname”);
and in old type of connectivity were
$link = mysql_connect(“localhost”, “username”, “password”);
mysql_select_db(“database”,$link);

Questions : 7 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 ?
Answers : 7 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).

Questions : 8 How can we create a database using PHP and MySQL?
Answers : 8 We can create MySQL database with the use of
mysql_create_db(“Database Name”)
Questions : 9 What are the differences between require and include?
Answers : 9 Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error .
Questions : 10  Can we use include (“xyz.PHP”) two times in a PHP page “index.PHP”?
Answers : 10   Yes we can use include(“xyz.php”) more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob
Questions : 11   What are the different tables(Engine) present in MySQL, which one is default?
Answers : 11  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)
6. EXAMPLE 
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)
Questions : 12 What are the differences between Get and post methods.
Answers : 12 There are some defference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good for send sensetive request
Questions : 13 How can I execute a PHP script using command line?
Answers : 13 Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument.
Questions : 14 Suppose your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ?
Answers : 14 In php.ini file:
set
short_open_tag=on
to make PHP support
Questions : 15 Shopping cart online validation i.e. how can we configure Paypal,
etc.?
Answers : 15 Nothing more we have to do only redirect to the payPal url after
submit all information needed by paypal like amount,adresss etc.
Questions : 16 What is meant by nl2br()?
Answers : 16 Inserts HTML line breaks (<BR />) before all newlines in a string.
Questions : 17 What is htaccess? Why do we use this and Where?
Answers : 17 .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.
Questions : 18 How we get IP address of client, previous reference page etc ?
Answers : 18 By using $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_REFERER’] etc.
Questions : 19 What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and
operating systems?
Answers : 19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.
Questions : 20 How can we encrypt and decrypt a data present in a MySQL table
using MySQL?
Answers : 20 AES_ENCRYPT () and AES_DECRYPT ()
Questions : 21 How can we encrypt the username and password using PHP?
Answers : 21 The functions in this section perform encryption and decryption, and
compression and uncompression:

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()
Questions : 22 What are the features and advantages of object-oriented
programming?
Answers : 22 One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system
Questions : 23 What are the differences between procedure-oriented languages and
object-oriented languages?
Answers : 23 There are lot of difference between procedure language and object oriented like below
1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model
2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern
3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .
Questions : 24 What is the use of friend function?
Answers : 24 Sometimes a function is best shared among a number of different
classes. Such functions can be declared either as member functions of
one class or as global functions. In either case they can be set to be
friends of other classes, by using a friend specifier in the class that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
A friend declaration is essentially a prototype for a member function,
but instead of requiring an implementation with the name of that class
attached by the double colon syntax, a global function or member
function of another class provides the match.
Questions : 25 What are the differences between public, private, protected,
static, transient, final and volatile?
Answer : 25 Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized. 
volatile:
 a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.
Questions : 26 What are the different types of errors in PHP?
Answer : 26 Three are three types of errors: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, as you will
see, you can change this default behavior.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, and PHP’s default behavior is to display them to the user
when they take place.
Questions : 27 What is the functionality of the function strstr and stristr?
Answers : 27 strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= ‘sonialouder@gmail.com’;
$domain = strstr($email, ‘@’);
echo $domain; // prints @gmail.com
here @ is the needle
stristr is case-insensitive means able not able to diffrenciate between a and A
Questions : 28 How can we submit a form without a submit button?
Answer : 28 Java script submit() function is used for submit form without submit button
on click call document.formname.submit()
Questions : 29 How can we convert asp pages to PHP pages?
Answer : 29 there are lots of tools available for asp to PHP conversion.
Questions : 30 What is the functionality of the function htmlentities?
Answer : 30 Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.
Questions : 31 How can we get second of the current time using date function?
Answer : 31 $second = date(“s”);
Questions : 32 How can we convert the time zones using PHP?
Answer : 32 For convert the time zones using PHP we have to first set time zone
By using PHP function date_default_timezone_set() 
If we want to set time zone of ‘Europe/London’ we have to call this funtion as
date_default_timezone_set(‘Europe/London’)
so Now generate the timestamp for that particular timezone, on Sept 1st, 2012 at 8 am
$pcds = mktime(8, 0, 0, 9, 1, 2012);
Now set the other timezone like US/Eastern
date_default_timezone_set(‘US/Eastern’);
date(DATE_RFC1123, $pcds) date(DATE_RFC1123, $pcds)
Output the date in a standard format (RFC1123)
Questions : 33 What is meant by urlencode and urldocode?
Answer : 33 URLencode returns a string in which all non-alphanumeric characters
except -_. have been replaced with a percent (%)
sign followed by two hex digits and spaces encoded as plus (+)
signs. It is encoded the same way that the posted data from a WWW form
is encoded, that is the same way as in
application/x-www-form-urlencoded media type.urldecode decodes any %##
encoding in the given string.
Questions : 34 What is the difference between the functions unlink and unset?
Answer : 34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.
Questions : 35 How can we register the variables into a session?
Answer : 35 $_SESSION[‘name’] = “sonia”;
Questions : 36 How can we get the properties (size, type, width, height) of an
image using PHP image functions?
Answer : 36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t
Questions : 37 How can we get the browser properties using PHP?
Answer : 37 By using 
$_SERVER['HTTP_USER_AGENT']
variable.
Questions : 38 What is the maximum size of a file that can be uploaded using PHP
and how can we change this?
Answer : 38 By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M
Questions : 39 How can we increase the execution time of a PHP script?
Answer : 39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds
Questions : 40 How can we take a backup of a MySQL table and how can we restore
it. ?
Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if
you just want to get a dump of the structure for a table!
Questions : 41 How can we optimize or increase the speed of a MySQL select
query?
Answer : 41
  • first of all instead of using select * from table1, use select
    column1, column2, column3.. from table1
  • Look for the opportunity to introduce index in the table you are
    querying.
  • use limit keyword if you are looking for any specific number of
    rows from the result set.
Questions : 42 How many ways can we get the value of current session id?
Answer : 42 session_id() returns the session id for the current session.
Questions : 43 How can we destroy the session, how can we unset the variable of
a session?
Answer : 43 session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables
Questions : 44 How can we set and destroy the cookie n php?
Answer : 44 By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ;
Set the cookies in past for destroy. like
setcookie(“user”, “sonia”, time()+3600); for set the cookie
setcookie(“user”, “”, time()-3600); for destroy or delete the cookies;
Questions : 45 How many ways we can pass the variable through the navigation
between the pages?
Answer : 45
  • GET/QueryString
  • POST
Questions : 46 What is the difference between ereg_replace() and eregi_replace()?
Answer : 46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.
Questions : 47 What are the different functions in sorting an array?
Answer : 47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().
Questions : 48 How can we know the count/number of elements of an array?
Answer : 48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
Questions : 49 what is session_set_save_handler in PHP?
Answer : 49 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.
Questions : 50 How can I know that a variable is a number or not using a
JavaScript?
Answer : 50 bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.
Questions : 51 List out some tools through which we can draw E-R diagrams for
mysql.
Answer : 51 Case Studio
Smart Draw
Questions : 52 How can I retrieve values from one database server and store them
in other database server using PHP?
Answer : 52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db1”, $db1);
$res1 = mysql_query(“query”,$db1);$db2 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db2”, $db2);
$res2 = mysql_query(“query”,$db2);At this point you can only fetch records from you previous ResultSet,
i.e $res1 – But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(“query”,$db1); //this will failSo how to solve that?take a look below.
$db1 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db1”, $db1);
$res1 = mysql_query(“query”,$db1);$db2 = mysql_connect(“host”,”user”,”pwd”, true)
mysql_select_db(“db2”, $db2);
$res2 = mysql_query(“query”,$db2);So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.now the following query will execute successfully.
$res3 = mysql_query(“query”,$db1);
Questions : 53 List out the predefined classes in PHP?
Answer : 53 Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
Questions : 54 How can I make a script that can be bi-language (supports
English, German)?
Answer : 54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.
Questions : 55 What are the difference between abstract class and interface?
Answer : 55 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.
Questions : 56 How can we send mail using JavaScript?
Answer : 56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.
Questions : 57 How can we repair a MySQL table?
Answer : 57 The syntex for repairing a MySQL table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified if the quick is given the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row
Questions : 58 What are the advantages of stored procedures, triggers, indexes?
Answer : 58 A stored procedure is a set of SQL commands that can be compiled and
stored in the server. Once this has been done, clients don’t need to
keep re-issuing the entire query but can refer to the stored procedure.
This provides better overall performance because the query has to be
parsed only once, and less information needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of
the work is done on the server side and less on the client (application)
side.Triggers will also be implemented. A trigger is effectively a type of
stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each
time a record is deleted from a transaction table and that stored
procedure automatically deletes the corresponding customer from a
customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read
through the entire table to find the relevant rows. The larger the
table, the more this costs. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the
middle of the data file without having to look at all the data. If a
table has 1,000 rows, this is at least 100 times faster than reading
sequentially. If you need to access most of the rows, it is faster to
read sequentially, because this minimizes disk seeks.
Questions : 59 What is the maximum length of a table name, database name, and
fieldname in MySQL?
Answer : 59 The following table describes the maximum length for each type of
identifier.

Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear in
identifiers:

Questions : 60 How many values can the SET function of MySQL take?
Answer : 60 MySQL set can take zero or more values but at the maximum it can
take 64 values
Questions : 61 What are the other commands to know the structure of table using
MySQL commands except explain command?
Answer : 61 describe Table-Name;
Questions : 62 How many tables will create when we create table, what are they?
Answer : 62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Questions : 63 What is the purpose of the following files having extensions 1) .frm
2) .myd 3) .myi? What do these files contain?
Answer : 63 In MySql, the default table type is MyISAM.
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.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Questions : 64 What is maximum size of a database in MySQL?
Answer : 64 If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM
storage engine in MySQL 3.23, the maximum table size was increased to
65536 terabytes (2567 – 1 bytes). With this larger allowed table size,
the maximum effective table size for MySQL databases is usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace
size is 64TB.
The following table lists some examples of operating system file-size
limits. This is only a rough guide and is not intended to be definitive.
For the most up-to-date information, be sure to check the documentation
specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
Questions : 65 Give the syntax of Grant and Revoke commands?
Answer : 65 The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password is simply the password of userThe generic syntax for revoke is as following
> REVOKE [rights] on [database/s] FROM [username@hostname]
now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
Questions : 66 Explain Normalization concept?
Answer : 66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal FormI have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table
Questions : 67 How can we find the number of rows in a table using MySQL?
Answer : 67 Use this for mysql
>SELECT COUNT(*) FROM table_name;
Questions : 68 How can we find the number of rows in a result set using PHP?
Answer : 68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
Questions : 69 How many ways we can we find the current date using MySQL?
Answer : 69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()
Questions : 70 What are the advantages and disadvantages of Cascading Style
Sheets?
Answer : 70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style SheetsAdvantagesClasses can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex
contexts. No additional downloads necessary to receive style informationDisadvantagesThis method can not control styles for multiple documents at onceInline StylesAdvantagesUseful for small quantities of style definitions. Can override other
style specification methods at the local level so only exceptions need
to be listed in conjunction with other style methodsDisadvantages

Does not distance style information from content (a main goal of
SGML/HTML). Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios

Questions : 71 What type of inheritance that PHP supports?
Answer : 71 In PHP an extended class is always dependent on a single base class,
that is, multiple inheritance is not supported. Classes are extended
using the keyword ‘extends’.
Questions : 72 What is the difference between Primary Key and
Unique key?
Answer : 72 Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.Unique Key: Unique Keys are used to uniquely identify each row in the
table. There can be one and only one row for each unique key value. So
NULL can be a unique key.There can be only one primary key for a table but there can be more
than one unique for a table.

Question : 73
what is garbage collection? default time ? refresh time?
Answer : 73 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: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100
Questions : 74 What are the advantages/disadvantages of MySQL and PHP?
Answer : 74 Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.
Questions : 75 What is the difference between GROUP BY and ORDER BY in Sql?
Answer : 75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
it should sort the result. If two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY
[col1],[col2],…,[coln]; Tels DBMS to group results with same value of
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average
Questions : 76 What is the difference between char and varchar data types?
Answer : 76 Set char to occupy n bytes and it will take n bytes even if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘romharshan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘romharshan’, if each
char takes a byte. rest 10 bytes will be free.
Questions : 77 What is the functionality of md5 function in PHP?
Answer : 77 Calculate the md5 hash of a string. The hash is a 32-character
hexadecimal number. I use it to generate keys which I use to identify
users etc. If I add random no techniques to it the md5 generated now
will be totally different for the same string I am using.
Questions : 78 How can I load data from a text file into a table?
Answer : 78 you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly
Questions : 79 How can we know the number of days between two given dates using
MySQL?
Answer : 79 SELECT DATEDIFF(“2007-03-07″,”2005-01-01”);
Questions : 80 How can we know the number of days between two given dates using PHP?
Answer : 80 $date1 = date(“Y-m-d”);
$date2 = “2006-08-15”;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
Questions : 81 How we load all classes that placed in different directory in one PHP File , means how to do auto load classes
Answer : 81 by using spl_autoload_register(‘autoloader::funtion’);Like belowclass autoloader{public static function moduleautoloader($class){

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/modules/{$class}.php”;

if (is_readable($path)) require $path;

}

public static function daoautoloader($class)

{

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/dataobjects/{$class}.php”;

if (is_readable($path)) require $path;

}

public static function includesautoloader($class)

{

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/includes/{$class}.php”;

if (is_readable($path)) require $path;

}

}

spl_autoload_register(‘autoloader::includesautoloader’);

spl_autoload_register(‘autoloader::daoautoloader’);

spl_autoload_register(‘autoloader::moduleautoloader’);

Questions : 82 How many types of Inheritances used in PHP and how we achieve it
Answer : 82 As far PHP concern it only support single Inheritance in scripting.
we can also use interface to achieve multiple inheritance.
Questions : 83 PHP how to know user has read the email?
Answers : 83 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;
}
Questions : 84 What are default session time and path?
Answers : 84 default session time in PHP is 1440 seconds or 24 minutes
Default session save path id temporary folder /tmp
Questions : 85 how to track user logged out or not? when user is idle ?
Answers : 85 By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.
Questions : 86 how to track no of user logged in ?
Answers : 86 whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.
Questions : 87 in PHP for pdf which library used?
Answers : 87 The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.
Questions : 88 for image work which library?
Answers : 88 we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.
Questions : 89 what is design pattern? explain all including singleton pattern?
Answers : 89 A design pattern is a general reusable solution to a commonly occurring problem in software design.
The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

Questions : 90 what are magic methods?
Answers : 90 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()
Questions : 91 what is magic quotes?
Answers : 91 Magic Quotes is a process that automagically escapes ncoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Questions : 92 what is cross site scripting? SQL injection?
Answers : 92 Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed
Questions : 93 what is URL rewriting?
Answers : 93 Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.
Questions : 94 what is the major php security hole? how to avoid?
Answers : 94 1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first.
2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes!
3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. If you don’t want the file contents to be seen, give the file a .php extension.
Questions : 95 whether PHP supports Microsoft SQL server ?
Answers : 95 The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.
Questions : 96 what is MVC? why its been used?
Answers : 96 Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:
A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code
Questions : 97 what is framework? how it works? what is advantage?
Answers : 97 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
Questions : 98 what is CURL?
Answers : 98 CURL means Client URL Library
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.
CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
Questions : 99 what is PDO ?
Answers : 99 The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code.While PDO has its advantages, such as a clean, simple, portable API but its maindisadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements.Just need to use below code for connect mysql using PDO
try {
$dbh = new PDO(“mysql:host=$hostname;dbname=databasename”, $username, $password);
$sql = “SELECT * FROM employee”;
foreach ($dbh->query($sql) as $row)
{
print $row[’employee_name’] .’ – ‘. $row[’employee_age’] ;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Questions : 100 What is PHP’s mysqli Extension?
Answers : 100 The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
=>Object-oriented interface
=>Support for Prepared Statements
=>Support for Multiple Statements
=>Support for Transactions
=>Enhanced debugging capabilities
=>Embedded server support
  1. What is the difference between $a and $$a?
  2. Who is the father of PHP?
  3. What are the differences between Get and post method.
  4. What does a special set of tags do in PHP?
  5. What’s the difference between include and require in PHP?
  6. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
  7. How do you pass a variable by Reference?
  8. How do you define a constant?
  9. Will comparison of string and integer work in PHP?
  10. Ternary conditional operator in PHP?
  11. How do I find out the number of parameters passed into function?
  12. How do you call a constructor for a parent class?
  13. What’s the special meaning of __sleep and __wakeup?
  14. What is the difference between characters 23 and x23?
  15. Difference between echo, print and printf.
  16. What’s the difference between htmlentities() and htmlspecialchars()?
  17. What’s the difference between md5(), crc32() and sha1() crypto on PHP?
  18. What is the difference between mysql_fetch_object and mysql_fetch_array?
  19. How many ways we can retrieve the data in the result set of MySQL using PHP?
  20. How can we create a database using PHP and MySQL?
  21. Can we use include (“abc.php”) two times in a PHP page “index.php”?
  22. What are the different table Engines present in MySQL?
  23. How can I execute a PHP script using command line?
  24. What is use of header() function in php ?
  25. What is meant by nl2br()?
  26. How we get IP address of client, previous reference page?
  27. What are the differences between public, private, protected,static,final and volatile?
  28. What are the different types of errors in PHP?
  29. What is the functionality of the function strstr and stristr?
  30. What are the differences between PHP 3 and PHP 4 and PHP 5?
  31. How can we get second of the current time using date function?
  32. How can we convert the time zones using PHP?
  33. What is meant by urlencode and urldocode?
  34. How can we register the variables into a session?
  35. How can we increase the execution time of a PHP script?
  36. How can we get the browser properties using PHP?
  37. What is the maximum size of a file that can be uploaded using PHP and how can we change this?
  38. How many ways can we get the value of current session id?
  39. How can we get the browser properties using PHP?
  40. How can we destroy the session?
  41. What are the different functions in sorting an array?
  42. How can we know the count/number of elements of an array?
  43. List out the predefined classes in PHP?
  44. What are the difference between abstract class and interface?
  45. How can we send mail using JavaScript?
  46. Explain Normalization concept?
  47. How can we find the number of rows in a result set using PHP?
  48. How many ways we can we find the current date using MySQL?
  49. What type of inheritance that PHP supports?
  50. What is the functionality of md5 function in PHP?
  51. How can we know the number of days between two given dates using PHP?
  52. PHP how to know user has read the email?
  53. What are default session time and path?
  54. what are magic methods?
  55. what is magic quotes?
  56. what is MVC? why its been used?
  57. what is CURL?
  58. What is PHP’s mysqli Extension?
  59. Difference between mysql_connect and mysql_pconnect?
  60. What is the use of obj_start()?
  61. What is the difference between session_register and $_session?
  62. How do you capture audio/video in PHP?
  63. How can I maintain the count of how many persons have hit my site?
  64. How would you initialize your strings with single quotes or double quotes?
  65. Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?
  66. How to prevent form hijacking in PHP?
  67. Where does the PHP session stored, either client side or server side?
  68. How can we submit a form without a submit button?
  69. What are new features that are in added in PHP5?
  70. How to handle drop down box change event without refreshing page?
  71. What Is a Persistent Cookie?
  72. What is meant by PEAR in php?
  73. How do we know browser properties?
  74. What is the difference between mysql_fetch_object and mysql_fetch_array?
  75. How do you create subdomains using PHP?
  76. What are the differences between require and include, include_once?
  77. Explain about the data types in PHP?
  78. Explain about switch statement in PHP?
  79. What Is a Session?
  80. Explain about PHP cookies?
  81. What would be the differences between PHP and Java?
  82. Explain about objects in PHP?
  83. What is the difference between $message and $$message?
  84. What is htaccess?
  85. How do you pass a variable by value?
  86. How can i get ip address?
  87. Explain about Functions in PHP?
  88. What is a PHP accelerator?
  89. Define about declare construct?
  90. What is the diffrence between Notify URL and Return URL?
  91. How To Read the Entire File into a Single String?
  92. Explain about Type Juggling in php?
  93. How to get the URL domain name in PHP?
  94. What type of headers have to be added in the mail function to attach a file?
  95. What is the maximum length of a table name, a database name, or a field name in MySQL?
  96. How To Convert Strings to Numbers in PHP?
  97. How To Turn On the Session Support in PHP?
  98. What is the difference between PHP4 and PHP5?
  99. What changes I have to do in php.ini file for file uploading?
  100. How many values can the SET function of MySQL take?
1. What is PHP?
  • PHP stand for Hypertext Preprocessor.
  • PHP is a Server Side Scripting Language.
  • PHP is a Open Source Software.
  • PHP free to download and use.
  • PHP scripts are executed on server.
  • PHP supports many databases such as MYSQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.,

PHP development began in 1994 when the Danish/Greenlandic programmerRasmus Lerdorf initially created a set of Perl scripts he called “Personal Home Page Tools” to maintain his personal homepage. Marco Tabini is the funder an publisher of PHP|architech.

2. What are the method available in form submitting?
GET and POST.
3. 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 POSTmethod 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.
4. How can we submit from without a submit button?
We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit(); function to submit the form.
5. How can we get the browser properties using php?
<?php
echo $_SERVER[‘HTTP_USER_AGENT’] . “\n\n”;
$browser = get_browser(null, true);
print_r($browser);
?>
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.
7. How can we register the variables into a session?
<?php
session_register($ur_session_var);
?>
8. How do you destroy a particular or all Sessions?
<?php
session_start();
// store session data
$_SESSION[‘views’]=1;
unset($_SESSION[‘views’]); // If you wish to delete some session data, you can use the unset()
session_destroy(); // You can also completely destroy the session by calling the session_destroy() function. session_destroy() will reset your session and you will lose all your stored session data.
?>
9. How many ways we can pass the variable through the navigation between the pages?
  • Register the variable into the session
  • Pass the variable as a cookie
  • Pass the variable as part of the URL
10. What are the different functions in sorting an array?
  • asort()
  • arsort()
  • ksort()
  • krsort()
  • uksort()
  • sort()
  • natsort()
  • rsort()
11. How can we know the total number of elements of Array?
  • sizeof($array_var)
  • count($array_var)

If we just pass a simple var instead of a an array it will return 1.

12. What type of headers that PHP supports?
$_SERVER[‘HTTP_ACCEPT’]
13. How can we extract string ‘abc.com’ from a string ‘http://info@abc.com’ using regular _expression of php?
We can use the preg_match() function with “/.*@(.*)$/” as the regular expression pattern.
For example:
<?php
preg_match(“/.*@(.*)$/”,”http://info@abc.com&#8221;,$data);
echo $data[1];
?>
14. How can we create a database using php?
mysql_create_db();
15. Explain include(), include_once, require() and require_once.
include()
The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution.include_once()
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once().require()
The require() function is identical to include(), except that it handles errors differently. The require() generates a fatal error, and the script will stop.require_once()
The required file is called only once when a page is open and further calling of the file will be ignored.
16. What are the different types of errors in php?
  • 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, as you will see, you can change this default behaviour.
  • 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.
  • 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, and PHP’s default behaviour is to display them to the user when they take place.

If we just pass a simple var instead of a an array it will return 1.

17. What are the Formatting and Printing Strings available in PHP?
Function Description
printf() Displays a formatted string
sprintf() Saves a formatted string in a variable
fprintf() Prints a formatted string to a file
number_format() Formats numbers as strings
18. How to find a length of a string?
strlen()
19. What is the functionality of the function strstr and stristr?
strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.
For example:
strstr(“user@example.com”,”@”) will return “@example.com”.stristr() is idential to strstr() except that it is case insensitive.
20. How can we get second of the current time using date function?
<?php
$second = date(“s”);
?>
21. What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.
unset() makes a variable undefined.
22. What is the difference between ereg_replace() and eregi_replace()?
eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.
23. What is the difference between characters 23 and \x23?
The first one is octal 23, the second is hex 23.
24. What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.PHP5 supports oops concepts and Zend engine 2 is used. Error supporting is increased in PHP5. XML and SQLLite will is increased in PHP5.
25. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
mysql_fetch_array:
Fetch a result row as an associative array and a numeric array.mysql_fetch_object:
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.mysql_fetch_row():
Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
26. In how many ways we can retrieve data in the result set of MYSQL using PHP?
mysql_fetch_array: – Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_assoc:- Fetch a result row as an associative array.
mysql_fetch_object:- Fetch a result row as an object.
mysql_fetch_row:- Get a result row as an enumerated array.
27. What are encryption functions in PHP?
CRYPT(), MD5()
28. What is the functionality of the function htmlentities?
htmlentities():- Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
29. How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds) Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed. When called,set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
30. How to set cookies?
setcookie(‘variable’,’value’,’time’);
variable – name of the cookie variable
value – value of the cookie variable
time – expiry time
Example:
<?php
setcookie(‘Test’,$i,time()+3600);
?>
Test – cookie variable name
$i – value of the variable ‘Test’
time()+3600 – denotes that the cookie will expire after an one hour
31. How to store the uploaded file to the final location?
move_uploaded_file( string filename, string destination)
32. What type of headers have to be added in the mail function to attach a file?
<?php
$boundary = ‘–‘ . md5( uniqid ( rand() ) );
$headers = “From: \”Me\”\n”;
$headers .= “MIME-Version: 1.0\n”;
$headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\””;

?>
33. How can we find the number of rows in a result set using php?
<?php
$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;
?>
34. How can we know the number of days between two given dates using php?
<?php
$tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
$lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
echo ($tomorrow-$lastmonth)/86400;
?>
35. How to open a file?
<?php
$file = fopen(“file.txt”,”r”);
?>
36. How many open modes available when a file open in PHP?
r  , r+  , w  , w+  , a  , a+  , x  , x+
37. Explain the types of string comparision function in PHP.
Function Descriptions
1. strcmp() Compares two strings (case sensitive)
2. strcasecmp() Compares two strings (not case sensitive)
3. strnatcmp(str1, str2); Compares two strings in ASCII order, but any numbers are compared numerically
4. strnatcasecmp(str1, str2); Compares two strings in ASCII order, case insensitive, numbers as numbers
5. strncasecomp() Compares two strings (not case sensitive) and allows you to specify how many characters to compare
6. strspn() Compares a string against characters represented by a mask
7. strcspn() Compares a string that contains characters not in the mask
38. Explain soundex() and metaphone().
soundex()
The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. he soundex() function can be used for spelling applications.
<?php
$str = “hello”;
echo soundex($str);

?>metaphone()
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications.
<?php
echo metaphone(“world”);
?>
39. Explain the types of functions for Splitting String?
Function Descriptions
1. split() Splits a string into an array by using a regular expression as the delimiter.
2. spliti() Splits a string into an array by a regular expression and is case insensitive.
3. str_split() Converts a string into an array where the size of the elements can be specified
4. preg_split() Splits up a string by a Perl compatible regular expression and returns an array of substrings
5. explode() Splits up a string by another string (not a regular expression) and returns an array
6. implode() Joins array elements together by a string and returns a string
40. Explain Whitespace Characters.
Whitespace Character ASCII Value(Decimal/Hex) Descriptions
” “ 32 (0x20)) An ordinary space
“\t” 9(0x0) A tab.
“\n” 10(0x0A) A newline (line feed).
“\r” 13(0x0D)) A carriage return.
“” 0(0x00)) The NULL-byte.
“\x0B” 11(0x0B)) A vertical tab.
41. What do you mean range()?
Starting from a low value and going to a high value, the range() function creates an array of consecutive integer or character values. It takes up to three arguments: a starting value, an ending value, and an increment value. If only two arguments are given, the increment value defaults to 1.
Example :
<?php
echo range(1,10); // Returns 1,2,3,4,5,6,7,8,9,10
?>
42. Explain Creating and Naming an Array.
Function Descriptions
1. array() Creates an array
2. array_combine() Creates an array by using one array for keys and another for its values
3. array_fill() Fills an array with values
4. array_pad() Pads an array to the specified length with a value
5. compact() Creates array containing variables and their values
6. range() Creates an array containing a range of elements
43. How to read and display a HTML source from the website url?
<?php
$filename=”http://www.kaptivate.in/&#8221;;
$fh=fopen(“$filename”, “r”);
while( !feof($fh) ){
$contents=htmlspecialchars(fgets($fh, 1024));
print “<pre>$contents</pre>”;
}
fclose($fh);

?>
44. How to display your correct URL of the current web page?
<?php
echo $_SERVER[‘PHP_SELF’];
?>
45. Explain $_FILES Superglobal Array.
Array Descriptions
$_FILES[‘userfile’][‘name’] The original name of the file on the client machine.
$_FILES[‘userfile’][‘type’] The MIME type of the file, if the browser provided this information. An example would be “image/gif”.
$_FILES[‘userfile’][‘size’] The size, in bytes, of the uploaded file.
$_FILES[‘userfile’][‘tmp_name’] The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[‘userfile’][‘error’] The error code associated with this file upload.
46. Explain mysql_error().
The mysql_error() message will tell us what was wrong with our query, similar to the message we would receive at the MySQL console.
47. What types of MYSQL function available in PHP?
Database Function Descriptions
1. mysql_connect() Opens a connection to a MySQL server.
2. mysql_pconnect() Opens a persistent connection.
3. mysql_selectdb() Selects the default database.
4. mysql_change_user() Changes the identity of the user logged on.
5. mysql_list_dbs Lists databases for this MySQL server.
6. mysql_list_tables Lists tables in the database.
48. How to get no. of rows using MYSQL function?
Database Function Descriptions
1. mysql_fetch_assoc() Returns one result row, as an associative array.
2. mysql_fetch_row() Returns one result row, as an array.
3. mysql_affected_rows() Returns number of rows affected by query.
4. mysql_num_rows() Returns number of rows selected.
5. mysql_list_dbs Lists databases for this MySQL server.
6. mysql_fetch_object() Returns a result row, as an object.
49. Explain mysql_errno().
Returns the numerical value of the error message from previous MySQL operation.
50. What types of MYSQL function available for affecting columns
Array Descriptions
mysql_fetch_field() Gets column information from a result and returns as an object.
mysql_field_name() Gets the name of the specified field in a result.
mysql_list_fields() Sets result pointer to a specified field offset.
mysql_num_fields() Gets number of fields in a result.
mysql_field_seek() Sets result pointer to a specified field offset.
mysql_field_type() Gets the type of the specified field in a result.
mysql_field_len() Returns the length of the specified field.
mysql_field_table() Gets name of the table the specified field is in.
mysql_tablename() Gets table name of field.
51. What is Constructors and Destructors?
CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
52. Why do we create an instance of a class?
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
53. What is properties of class?
Class member variables are called “properties”. We may also see them referred to using other terms such as “attributes” or “fields”, but for the purposes of this reference we will use “properties”. They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
54. Explain Constant in Class.
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that we don’t use the $ symbol to declare or use them.The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
55. Explain the visibility of the property or method.
The visibility of a property or method must be defined by prefixing the declaration with the keywords public, protected or private.

  • Class members declared public can be accessed everywhere.
  • Members declared protected can be accessed only within the class itself and by inherited and parent classes.
  • Members declared as private may only be accessed by the class that defines the member.
Q:1 What are the differences between Get and post methods in form submitting.
give the case where we can use get and we can use post methods?
A:1

When to use GET or POST

The HTML 2.0 specification says, in section Form
Submission (and the HTML 4.0 specification repeats this with minor
stylistic changes):

–>If the processing of a form is idempotent
(i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side
effects (for example, modification of a database or subscription to
a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” – -, the user agent
takes the value of action, appends a ? to it, then appends the form
data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In
this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post
transaction using the value of the action attribute and a message
created according to the content type specified by the enctype
attribute.

Quote from CGI FAQ

Firstly, the the HTTP protocol specifies
differing usages for the two methods. GET requests should always be
idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more
identical requests will have no further effect.

This is a theoretical point which is also good
advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting
in two identical database or
guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the
user before
re-submitting a POST request. This means you’re far less likely to
get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for
idempotent operations, such as querying a database, though it
matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to
be change when user resubmits. And GET
when it does not matter.

Q:2 Who is the father of PHP and explain the changes in PHP versions?
A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3
is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current
generation of PHP, which uses the
Zend engine
under the
hood. PHP 5 uses
Zend engine 2 which,
among other things, offers many additionalOOP features
Q:3 How can we submit a form without a submit button?
A:3 The main idea behind this is to use Java script submit() function in
order to submit the form without explicitly clicking any submit button.
You can attach the document.formname.submit() method to onclick,
onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the
form after xx seconds once the loading is done (can be seen in online
test sites).
Q:4 In how many ways we can retrieve the data in the result set of
MySQL using PHP?
A:4 You can do it by 4 Ways1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
Q:5 What is the difference between mysql_fetch_object and
mysql_fetch_array?
A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference –
an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).
Q:6 What is the difference between $message and $$message?
A:6 It is a classic example of PHP’s variable variables. take the
following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the
$$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like
this${$message} => $mizanSometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used dynamically.
Q:7 How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?
A:7 preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];
Q:8 How can we create a database using PHP and MySQL?
A:8 We can create MySQL database with the use of
mysql_create_db(“Database Name”)
Q:9 What are the differences between require and include,
include_once and require_once?
A:9 The include() statement includes
and evaluates the specified file.The documentation below also applies to
require(). The two constructs
are identical in every way except how they handle
failure. include() produces a
Warning while require() results
in a Fatal Error. In other words, use
require() if you want a missing
file to halt processing of the page.
include()
does not behave this way, the script will
continue regardless.The include_once()
statement includes and evaluates the
specified file during the execution of
the script. This is a behavior similar
to the include()
statement, with the only difference
being that if the code from a file has
already been included, it will not be
included again. As the name suggests, it
will be included just once.include_once()
should be used in cases where the same
file might be included and evaluated
more than once during a particular
execution of a script, and you want to
be sure that it is included exactly once
to avoid problems with function
redefinitions, variable value
reassignments, etc.require_once()
should be used in cases where the same
file might be included and evaluated
more than once during a particular
execution of a script, and you want to
be sure that it is included exactly once
to avoid problems with function
redefinitions, variable value
reassignments, etc.
Q:10 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:10 Yes we can use include() more than one time in any page though it is
not a very good practice.
Q:11 What are the different tables present in MySQL, which type of
table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?
A:11 Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.
Q:12 Functions in IMAP, POP3 AND LDAP?
A:12 You can find these specific information in PHP Manual.
Q:13 How can I execute a PHP script using command line?
A:13 As of version 4.3.0, PHP supports a new SAPI type (Server
Application Programming Interface) named CLI which means Command Line
Interface. Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument. For
example, “php myScript.php”, assuming “php” is the command to invoke the
CLI program.
Be aware that if your PHP script was written for the Web CGI interface,
it may not execute properly in command line environment.
Q:14 Suppose your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ?
A:14 In php.ini file:
set
short_open_tag=on
to make PHP support
Q:15 Shopping cart online validation i.e. how can we configure Paypal,
etc.?
A:15 We can find the detail documentation about different paypal
integration process at the following site

PayPal PHP
SDK : http://www.paypaldev.org

Q:16 What is meant by nl2br()?
A:16 Inserts HTML line breaks (<BR />) before all newlines in a string
string nl2br (string); Returns string with ” inserted before all
newlines. For example: echo nl2br(”god bless\n you”) will output “god
bless <br /> you” to your browser.
Q:17 Draw the architecture of Zend engine?
A:17 The Zend Engine is the internal compiler and runtime engine used by
PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as
follows:
The PHP script was loaded by the Zend Engine and compiled into Zend
opcode. Opcodes, short for operation codes, are low level binary
instructions. Then the opcode was executed and the HTML generated sent
to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you
speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.
Q:18 What are the current versions of apache, PHP, and MySQL?
A:18 As of February, 2007 the current versions arePHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4Note: visit www.php.net,

http://dev.mysql.com/downloads/mysql/
,
www.apache.org to get current
versions.
Q:19 What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and
operating systems?
A:19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.
Q:20 How can we encrypt and decrypt a data present in a MySQL table
using MySQL?
A:20 AES_ENCRYPT () and AES_DECRYPT ()
Q:21 How can we encrypt the username and password using PHP?
A:21 The functions in this section perform encryption and decryption, and
compression and uncompression:

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

 

Q:22 What are the features and advantages of object-oriented
programming?
A:22 One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system
Q:23 What are the differences between procedure-oriented languages and
object-oriented languages?
A:23 Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can
affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code
that manages the date), it is often simply cut and pasted into each
program (i.e., a change log, order function, fulfillment system, etc).
If a date change is needed (i.e., Y2K when the code needed to be changed
to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which
the instructions operates on) are kept separate. Multiple sets of code
can access and modify one set of data. One set of code may rely on data
in multiple places. Multiple sets of code and data are required to work
together. Changes made to any of the code sets and data sets can cause
problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the
term “component” has also been used to describe an object.) An object is
an abstraction of a set of real-world things (for example, an object may
be created around “date”) The object would contain all information and
functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it
is a business day or a holiday, etc., See Fig. 1). Ideally, information
about a particular thing should reside in only one place in a system.
The information within an object is encapsulated (or hidden) from the
rest of the system.
A system is composed of multiple objects (i.e., date function, reports,
order processing, etc., See Fig 2). When one object needs information
from another object, a request is sent asking for specific information.
(for example, a report object may need to know what today’s date is and
will send a request to the date object) These requests are called
messages and each object has an interface that manages messages.
OO programming languages include features such as “class”, “instance”,
“inheritance”, and “polymorphism” that increase the power and
flexibility of an object.
Q:24 What is the use of friend function?
A:24 Sometimes a function is best shared among a number of different
classes. Such functions can be declared either as member functions of
one class or as global functions. In either case they can be set to be
friends of other classes, by using a friend specifier in the class that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
A friend declaration is essentially a prototype for a member function,
but instead of requiring an implementation with the name of that class
attached by the double colon syntax, a global function or member
function of another class provides the match.
Q:25 What are the differences between public, private, protected,
static, transient, final and volatile?
A:25 Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile:
a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.
Q:26 What are the different types of errors in PHP?
A:26 Three are three types of errors:

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, as you will see, you can change this default behavior.

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, and PHP’s default behavior is to display them to the user when they take place.

Q:27 What is the functionality of the function strstr and stristr?
A:27 strstr:Returns part of haystack
string from the first occurrence of
needle to the end of
haystack.If needle is not found,
returns FALSE.

If needle is not a
string, it is converted to an integer and applied as the
ordinal value of a character.

This function is case-sensitive. For
case-insensitive searches, use
stristr().

Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?
A:28 Please read the release notes at
http://www.php.net.
Q:29 How can we convert asp pages to PHP pages?
A:29 there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available athttp://asp2php.naken.cc./
Q:30 What is the functionality of the function htmlentities?
A:30 Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.
Q:31 How can we get second of the current time using date function?
A:31 $second = date(”s”);
Q:32 How can we convert the time zones using PHP?
A:32 By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0

<?php
// Discover what 8am in Tokyo relates to on the East Coast of the US    

// Set the default timezone to Tokyo time:
date_default_timezone_set('Asia/Tokyo');    

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);    

// Now set the timezone back to US/Eastern
date_default_timezone_set('US/Eastern');    

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>
Q:33 What is meant by urlencode and urldocode?
A:33 URLencode returns a string in which all non-alphanumeric characters
except -_. have been replaced with a percent (%)
sign followed by two hex digits and spaces encoded as plus (+)
signs. It is encoded the same way that the posted data from a WWW form
is encoded, that is the same way as in
application/x-www-form-urlencoded media type.urldecode decodes any %##
encoding in the given string.
Q:34 What is the difference between the functions unlink and unset?
A:34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.
Q:35 How can we register the variables into a session?
A:35 $_SESSION[’name’] = “Mizan”;
Q:36 How can we get the properties (size, type, width, height) of an
image using PHP image functions?
A:36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t
Q:37 How can we get the browser properties using PHP?
A:37 By using
$_SERVER['HTTP_USER_AGENT']
variable.
Q:38 What is the maximum size of a file that can be uploaded using PHP
and how can we change this?
A:38 By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M
Q:39 How can we increase the execution time of a PHP script?
A:39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds
Q:40 How can we take a backup of a MySQL table and how can we restore
it. ?
A:40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if
you just want to get a dump of the structure for a table!
Q:41 How can we optimize or increase the speed of a MySQL select
query?
A:41
  • first of all instead of using select * from table1, use select
    column1, column2, column3.. from table1
  • Look for the opportunity to introduce index in the table you are
    querying.
  • use limit keyword if you are looking for any specific number of
    rows from the result set.
Q:42 How many ways can we get the value of current session id?
A:42 session_id() returns the session id for the current session.
Q:43 How can we destroy the session, how can we unset the variable of
a session?
A:43 session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables
Q:44 How can we destroy the cookie?
A:44 Set the cookie in past.
Q:45 How many ways we can pass the variable through the navigation
between the pages?
A:45
  • GET/QueryString
  • POST
Q:46 What is the difference between ereg_replace() and eregi_replace()?
A:46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.
Q:47 What are the different functions in sorting an array?
A:47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().
Q:48 How can we know the count/number of elements of an array?
A:48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
Q:49 What is the PHP predefined variable that tells the What types of
images that PHP supports?
A:49 Though i am not sure if this is wrong or not, With the exif
extension you are able to work with image meta data.
Q:50 How can I know that a variable is a number or not using a
JavaScript?
A:50 bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.
Q:51 List out some tools through which we can draw E-R diagrams for
mysql.
A:51 Case Studio
Smart Draw
Q:52 How can I retrieve values from one database server and store them
in other database server using PHP?
A:52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);At this point you can only fetch records from you previous ResultSet,
i.e $res1 – But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that?take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”, true)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);

So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.

now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Thanks goes to Hasan and Hasin for this solution.

Q:53 List out the predefined classes in PHP?
A:53 Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
Q:54 How can I make a script that can be bi-language (supports
English, German)?
A:54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.
Q:55 What are the difference between abstract class and interface?
A:55 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.
Q:56 How can we send mail using JavaScript?
A:56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.
Q:57 How can we repair a MySQL table?
A:57 The syntex for repairing a MySQL table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified if the quick is given the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row
Q:58 What are the advantages of stored procedures, triggers, indexes?
A:58 A stored procedure is a set of SQL commands that can be compiled and
stored in the server. Once this has been done, clients don’t need to
keep re-issuing the entire query but can refer to the stored procedure.
This provides better overall performance because the query has to be
parsed only once, and less information needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of
the work is done on the server side and less on the client (application)
side.Triggers will also be implemented. A trigger is effectively a type of
stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each
time a record is deleted from a transaction table and that stored
procedure automatically deletes the corresponding customer from a
customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read
through the entire table to find the relevant rows. The larger the
table, the more this costs. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the
middle of the data file without having to look at all the data. If a
table has 1,000 rows, this is at least 100 times faster than reading
sequentially. If you need to access most of the rows, it is faster to
read sequentially, because this minimizes disk seeks.
Q:59 What is the maximum length of a table name, database name, and
fieldname in MySQL?
A:59 The following table describes the maximum length for each type of
identifier.

Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear in
identifiers:

Q:60 How many values can the SET function of MySQL take?
A:60 MySQL set can take zero or more values but at the maximum it can
take 64 values
Q:61 What are the other commands to know the structure of table using
MySQL commands except explain command?
A:61 describe Table-Name;
Q:62 How many tables will create when we create table, what are they?
A:62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Q:63 What is the purpose of the following files having extensions 1) .frm
2) .myd 3) .myi? What do these files contain?
A:63 In MySql, the default table type is MyISAM.
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.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Q:64 What is maximum size of a database in MySQL?
A:64 If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM
storage engine in MySQL 3.23, the maximum table size was increased to
65536 terabytes (2567 – 1 bytes). With this larger allowed table size,
the maximum effective table size for MySQL databases is usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace
size is 64TB.
The following table lists some examples of operating system file-size
limits. This is only a rough guide and is not intended to be definitive.
For the most up-to-date information, be sure to check the documentation
specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
Q:65 Give the syntax of Grant and Revoke commands?
A:65 The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password is simply the password of userThe generic syntax for revoke is as following
> REVOKE [rights] on [database/s] FROM [username@hostname]
now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
Q:66 Explain Normalization concept?
A:66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal FormI have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table
Q:67 How can we find the number of rows in a table using MySQL?
A:67 Use this for mysql
>SELECT COUNT(*) FROM table_name;
Q:68 How can we find the number of rows in a result set using PHP?
A:68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
Q:69 How many ways we can we find the current date using MySQL?
A:69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()
Q:70 What are the advantages and disadvantages of Cascading Style
Sheets?
A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style SheetsAdvantagesClasses can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex
contexts. No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions. Can override other
style specification methods at the local level so only exceptions need
to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of
SGML/HTML). Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios

Q:71 What type of inheritance that PHP supports?
A:71 In PHP an extended class is always dependent on a single base class,
that is, multiple inheritance is not supported. Classes are extended
using the keyword ‘extends’.
Q:72 What is the difference between Primary Key and
Unique key?
A:72 Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.Unique Key: Unique Keys are used to uniquely identify each row in the
table. There can be one and only one row for each unique key value. So
NULL can be a unique key.There can be only one primary key for a table but there can be more
than one unique for a table.

Q:73
The structure of table view buyers is as follows:

Field

Type

Null

Key

Default

Extra

user_pri_id int(15) PRI null auto_increment
userid varchar(10) YES null

the value of user_pri_id the last row 999 then What will happen in
the following conditions?

Condition1: Delete all the rows and insert another row then.
What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and
insert another row then. What is the value for this auto incremented
field user_pri_id

A:73 In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000
Q:74 What are the advantages/disadvantages of MySQL and PHP?
A:74 Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.
Q:75 What is the difference between GROUP BY and ORDER BY in Sql?
A:75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
it should sort the result. If two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY
[col1],[col2],…,[coln]; Tels DBMS to group results with same value of
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average
Q:76 What is the difference between char and varchar data types?
A:76 Set char to occupy n bytes and it will take n bytes even if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char takes a byte. rest 10 bytes will be free.
Q:77 What is the functionality of md5 function in PHP?
A:77 Calculate the md5 hash of a string. The hash is a 32-character
hexadecimal number. I use it to generate keys which I use to identify
users etc. If I add random no techniques to it the md5 generated now
will be totally different for the same string I am using.
Q:78 How can I load data from a text file into a table?
A:78 you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly
Q:79 How can we know the number of days between two given dates using
MySQL?
A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);
Q:80 How can we know the number of days between two given dates using
PHP?
A:80 $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15′;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

This page has the following sub pages.