Sunday, April 14, 2013

PHP Interview Questions



11.)    What is difference between session and cookie?
Cookies
- stored on CLIENT machine
- amount of data to be stored is LIMITED
- it can only store STRINGS
- quite FASTER than a session
Session
- stored on SERVER machine
- amount of data to be stored is NOT LIMITED
- it can store OBJECTS
- quite SLOWER as compared to cookies
2) Difference between implode and explode function?
The implode() function takes an already existing array as
it's argument, and concatenates the contents of
each element in the array into a string.
where as explode() function performs reverse to implode()
function. It splits the string into items by a
delimiter, such as a dash, ampersand, space and places each
item into a new array.
Another Answer:- Implode() Function
The implode function is used to "join elements of an array with a string".
The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice. 
The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.
Suppose you have an array like this $arr = Array ("A","E","I","O","U");

and you wish to combine it into a string, by putting the separator '-' between each element of the array.

How to do that?

$str = implode("-",$arr);

So your resulting string variable $str will be contain:
A-E-I-O-U

Syntax
implode (separator , array)
Example1

<html>
<
body bgcolor="pink">
<
h3>Implode Function</h3>
<?php
$arr=array ('I','am','simple','boy!');
echo implode(" ",$arr);
?>
</body>
</html>
Output
 Explode() Function
The explode function is used to "Split a string by a specified string into pieces i.e. it breaks a string into an array".
The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.
For example you have a string

$str="A E I O U";

now you want to make each name as an element of an array and access it individually so what you do:

$arr = explode(",", $str);

means : we have made pieces of string $text based on separator ','
and put the resulting array in variable $arr

So I used print_r ($arr); and the results are the following:

Array(
[0] => A
[1] => E
[2] => I
[3] => O
[4] => U
)

which is equal to:

$arr = Array ("A","E","I","O","U");

Syntax

explode (separator,string,limit)
 
Example1

<html>
<
body bgcolor="pink">
<
h3>Explode Function</h3>
<?php
$str="I am simple boy!";
print_r(explode(
" ",$str));
?>
</body>
</html>
Output
3)difference between Innodb and Myisam?
There is foolowing Differences between MYISAM and InnoDB
ENGINE:-
1)MYISAM does not support the foreign key constraint and
transaction but InnoDB support it.
2)MYISAM is faster then the InnoDB but in case of perforing
the count operation it takes more time then the InnoDB.
3) MYISAM occupies less memory sapce for tables rather than
InnoDB tables.
4)difference between unlink and unset?
unlink-deletes the file
unset-unsets the variable
5)string function?
PHP String Functions
PHP: indicates the earliest version of PHP that supports the function.
Function
Description
PHP
Returns a string with backslashes in front of the specified characters
4
Returns a string with backslashes in front of predefined characters
3
Converts a string of ASCII characters to hexadecimal values
3
Alias of rtrim()
3
Returns a character from a specified ASCII value
3
Splits a string into a series of smaller parts
3
Converts a string from one Cyrillic character-set to another
3
Decodes a uuencoded string
5
Encodes a string using the uuencode algorithm
5
Returns how many times an ASCII character occurs within a string and returns the information
4
Calculates a 32-bit CRC for a string
4
One-way string encryption (hashing)
3
Outputs strings
3













6)array and array function?
Function
Description
Creates an array
Changes all keys in an array to lowercase or uppercase
Splits an array into chunks of arrays
Creates an array by using the elements from one "keys" array and one "values" array
Counts all the values of an array
Compare arrays, and returns the differences (compare values only)
Compare arrays, and returns the differences (compare keys and values)
Compare arrays, and returns the differences (compare keys only)
Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)

Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

7)difference between echo and print?
Comparison chart
Echo (PHP)
Print (PHP)
Parameters:
echo can take more than one parameter when used without parentheses. The syntax is echo expression [, expression[, expression] ... ]. Note that echo ($arg1,$arg2) is invalid.
print only takes one parameter.
Return value:
echo does not return any value
print always returns 1 (integer)
Syntax:
void echo ( string $arg1 [, string $... ] )
int print ( string $arg )
What is it?:
In PHP, echo is not a function but a language construct.
In PHP, print is not a really function but a language construct. However, it behaves like a function in that it returns a value.
8)What is the difference between == and === in PHP?
When comparing values in PHP for equality you can use either the == operator or the === operator. What’s the difference between the 2? Well, it’s quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).
9)Diffrence between GET and POST?
GET
-Get method is default method.In this data is send with URL Not in a secured manner.
-GET form contents are passed as part of the URL, as a QUERY STRING.
- GET method have not security because of data view in addressbar. For ex: we can not use this method for checking login
- We can bookmark link with this method
- Server can log all action
- because of server log, we can pass 255 char. as query String.


POST
-POST form contents are passed to the script as an input file As a result, much more form data can be passed, since you can't run into the limit on the length of a URL or the length of a command line or command line argument on the server.
- POST method have security of data.
- We can not bookmark page link
- We can pass unlimited data by this method as query string In GET method.
-In POST method data is submitted as a part of http request
- data is not visible in the url
- It is more secure but slower as compared to GET.
10)Difference between include and require and require_once?
Get method is default method In this data is send with URL
Not a secure manner.
In Post method data send in body portion
Another  Question:-
In GET method
- data is submitted as a part of url
- data is visible to the user
- it is not secure but fast and quick
In POST method
- data is submitted as a part of http request
- data is not visible in the url
- it is more secure but slower as compared to GET
11)Current version of Apache, Php and Mysql.
PHP: PHP 5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1
12)Difference types of error in PHP?
Here are three basic types of runtime errors in PHP:

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

Internally, these variations are represented by twelve different error types

The following is a list of the error codes returned by PHP.

E_ERROR: Fatal error. Terminates the script.

E_WARNING: Warning that does not end the script.

E_PARSE: There is an error in the parser.

E_NOTICE: Non-fatal error in the code.

E_CORE_ERROR: Fatal error in the PHP installation.

E_CORE_WARNING: Warnings resulting form an error in the PHP installation.

E_COMPILE_ERROR: Fatal error that occurs when script is compiled.

E_USER_ERROR: Error generated by programmer's code.

E_USER_WARNING: Warning generated by programmer's code.

13)orderby, groupby and having in mysql
Groupby: It is a way to sub-total your results,or perform
some other 'aggregate' functions on them.
Orderby: It is a simply a way to sort your results. It
doesn't affect what shows up in your result set,only what
order it is displayed.
14)join in mysql
INNER JOIN DISPLAYS ONLY THE RECORDS WHICH ARE SATISFYING
THE JOINING CONDITION,WHERE AS IN AN OUTER JOIN IT DISPLAYS
THE RECORDS WHICH ARE SATISFYING THE CONDITION AND ALSO
WHICH ARE NOT SATIFYING THE CONDITION ALSO.
FOR EXAMPLE  TAKE EMP AND DEPT TABLE.
INNER JOIN QUERY:
SELECT EMPNO,ENAME,SAL,DEPT.DEPTNO,DNAME,LOC FROM EMP INNER
JOIN DEPT ON(EMP.DEPTNO=DEPT.DEPTNO)
OUTER JOIN QUERY:
SELECT EMPNO,ENAME,SAL,DEPT.DEPTNO,DNAME,LOC FROM EMP RIGHT
OUTER JOIN DEPT ON(EMP.DEPTNO=DEPT.DEPTNO).
IN INNER JOIN IT DISPLAYS ONLY 10,20 & 30 DEPARTMENTS.
IN OUTER JOIN IT DISPLAYS 10,20,30 AND 40 DEPARTMENTS.
TAKE DEFAULT TABLES FOR EXECUTION
Answer
#
2
Inner join: displays only matching record from 2 tables
Outer join:
Left outer join display all the records from 1st table even
if dont have matching record in 2nd table
rignt outer join display all the record from the 2nd table
even if there is not matching record in 1st table

15)Date and time in mysql
MySQL Time - Formats
There are three different types of time data types in MySQL: TIME, DATETIME, and TIMESTAMP. If you would like to learn more about DATETIME and TIMESTAMP, then check out our MySQL Date section, as we've covered them there. This lesson will just be covering the basics of using TIME.
MySQL Time - TIME
First you need to create a MySQL table with a TIME type. We have one already created if you want to use it: timeplayground.sql.
The TIME data type can be used to store actual times as well as the amount of time between two points in time (like the time between now and the weekend) that may sometimes be larger than 23 hours. H - Hour; M - Minute; S - Second.
Standard format: HH:MM:SS
Extended hour format: HHH:MM:SS
Time Range: -838:59:50 to 838:59:59
When manually entering a time into MySQL it is highly recommended that you use the exact format show above. MySQL allows for many different ways to enter a time, but they don't always behave as you would expect. Using the standard/extended format we have shown above will help you avoid annoying problems.
Below we have entered 3 manual times into MySQL. The first is done in the recommended format, the second is a shorthand version of the first and the final example is outside the allowed time range.
PHP & MySQL Code:
<?php
//This assumes you have already created the 'dateplayground' table
//Connect to DB
$query_manual1 = "INSERT INTO timeplayground (dp_name, dp_time)
            VALUES ('TIME: Manual Time', '12:10:00')"; //perfectly done
$query_manual2 = "INSERT INTO timeplayground (dp_name, dp_time)
            VALUES ('TIME: Manual Time', '1210')"; // will this shorthand work?
$query_manual3 = "INSERT INTO timeplayground (dp_name, dp_time)
            VALUES ('TIME: Manual Time', '978:31:12')"; //how about this?

mysql_query($query_manual1) or die(mysql_error());
mysql_query($query_manual2) or die(mysql_error());
mysql_query($query_manual3) or die(mysql_error());
?>
MySQL Time - NOW()
To get the current time, use MySQL's built in function NOW(). NOW() contains both the date and time information, but MySQL is smart enough to just use the data needed for TIME.
PHP & MySQL Code:
<?php
$query_auto = "INSERT INTO timeplayground (dp_name, dp_time)
            VALUE ('TIME: Auto NOW()', NOW() )";

mysql_query($query_auto) or die(mysql_error());
?>
MySQL timeplayground.sql Displayed
Below is a small PHP script to spit out a rough version of our timeplayground.sql table.
PHP & MySQL Code:
<?php
$query = "SELECT * FROM timeplayground";
$result = mysql_query($query) or die(mysql_error());

echo "<table border='1'><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++){
            echo "<th>".mysql_field_name($result, $i)."</th>";
}
echo "</tr>";
while($row = mysql_fetch_array($result)){
            echo "<tr>";
            for($i = 0; $i < mysql_num_fields($result); $i++){
                        echo "<td>". $row[$i] ."</td>";
            }
            echo "</tr>";
}

echo "</table>";
?>
Finished timeplayground.sql Display:
dp_name
dp_time
TIME: Manual Time
12:10:00
TIME: Manual Time
00:12:10
TIME: Manual Time
838:59:59
TIME: Auto NOW()
14:30:36
Our first manual time was handled just fine, but our second one did not. MySQL interpreted 1210 as MM:SS instead of HH:MM as we assumed. This is why it's best to use the formats we've described at the beginning.
The third manual entry was changed from 978:31:12 to 838:59:59, so that it would be within TIME's range.

16)subqueries in mysql
A subquery is, in essence, a SELECT statement that is most often used as part of another SELECT statement, but could also be used with an INSERT, UPDATE, or DELETE and other statements. Subqueries are used in order to achieve very complex searches and complex reports, as well as for various optimizations. You can use a subquery in the FROM clause of a SELECT to allow you to have essentially any number of GROUP BY clauses to further and further refine your result.
17)Difference between connect and pconnect?
mysql_connect opens up a database connection every time a page is loaded. mysql_pconnect opens up a connection, and keeps it open across multiple requests.

mysql_pconnect uses less resources, because it does not need to establish a database connection every time a page is loaded.
Answer:- In this article I discuss the two MySQL built-in connection functions "mysql_Connect()" and "mysql_Pconnect()" in PHP. Suppose you want to insert some data into the emp detail table of your database in a PHP application. The first thing that must be done is to create a connection for the table data for the operations and that is done using mysql_connect(), because before you can access data in a database, you must create a connection to the database and after performing all the operations on the database, you should close the connection using the mysql_close() function, but a Pconnection is already open and available for use at any time; the mysql_pconnect() function will not be closed and will persist for future use.
Syntax
Mysql_connect('localhost');
Example
<?php
//use for connection
{
$con= mysql_connect('localhost');
echo "$con";
}
?>
Syntax
Mysql_pconnect('localhost');
 The Pconnect function uses minimumal resourses because the mysql_pconnect() function is already connected with your database connection; it does need to have a connection established with the database every time the page is loaded, for when you want to persistent a connection.
When  you want a connection then you first find a persistent connection link that is already open with the same host, username and password. The persistent connection is make a max connection and connected max clients. This connection is a multi-credential connection.
Example
<?php
//use for persistence connection
$conn = mysql_pconnect('localhost');
echo $conn;
?>
Output
18)insert, update,delete command in mysql
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)




Update Data In a Database
The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Delete Data In a Database
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name
WHERE some_column = some_value
19)Unique key, primary key and foreign key in mysql.
Primary key - Primary key means main key
def:- A primary key is one which uniquely identifies a row
of a table. this key does not allow null values and also
does not allow duplicate values. for ex,
     empno   empname   salary
       1      firoz     35000
       2      basha     34000
       3      chintoo   40000
it will not the values as follows:
1      firoz      35000
1      basha      34000
       chintoo    35000
Unique key -  single and main key
            A unique is one which uniquely identifies a row
of a table, but there is a difference like it will not
allow duplicate values and it will any number of  allow
null values(In oracle).
it allows only a single null value(In sql server 2000)
Both will function in a similar way but a slight difference
will be there. So, decalaring it as a primary key is the
best one.
foreign key - a foreign key is one which will refer to a
primary key of another table
for ex,
       emp_table                         dept_table
empno empname salary  deptno         deptno deptname
In the above relation, deptno is there in emp_table which
is a primary key of dept_table. that means, deptno is
refering the dept_table.
20)Mysql function.
Table of Contents
mysql_affected_rows — Get number of affected rows in previous MySQL operation
mysql_client_encoding — Returns the name of the character set
mysql_close — Close MySQL connection
mysql_connect — Open a connection to a MySQL Server
mysql_create_db — Create a MySQL database
mysql_data_seek — Move internal result pointer
mysql_db_name — Retrieves database name from the call to mysql_list_dbs
mysql_db_query — Selects a database and executes a query on it
mysql_drop_db — Drop (delete) a MySQL database

5 comments:

  1. This is a wonderful article. I can see that you have done a lot of research and your subject knowledge is good and impressive.
    This is Nitin, I also like to write for an education blog Clear IIT Medical - This is an online blog for students who want to prepare for India's most difficult entrance exams - IIT JEE and NEET This is a free blog and provide free study material, quiz and notes to those who can't afford to pay hefty fees of coaching institutes. I write free of cost for the good cause. I know you must be busy with your work but if you could take out some time from your busy schedule and have a look at it. I saw a good collection of articles. If you only write a few words about this blog then it can help a lot of students out there. Thanks!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Very nice article! I write for educational blogs. I make a collection of wonderful educational blogs from where I could take inspiration for writing. This article really inspires me though it is a little different from my domain but nonetheless it is a good writing. I sometime write for education site blogs
    Clear Exam Let me know your thoughts if I could contribute to your blog too.

    ReplyDelete
  4. Wow! Such an articulate post it is! I am a fan of your writing. Being a new writer, it's always good to see inspiring posts like this. I am a management graduate and write for 12th pass students for various career options. I write for a good blog:
    Clear Law Entrance I want to write about a lot of things out there, please guide me on how I can become a good blogger.

    ReplyDelete
  5. Hey, it's Smriti. Your article is a good one. I must say not everybody knows how to write blogs and make them look professional. Being a law student I always look for data points like charts, analysis in articles. Yours seems to give justice to the topic. My personal style includes a lot of graphs, numbers and informative videos. I write on
    Success Mantra for law related exams.

    ReplyDelete