OOP in PHP5
What is an object?
Ans: A group information that holds the information about data,
methods from a class.
What is a class?
Ans : A collection of data and methods
What is an interface?
Ans: In OOP model inheritance is used to provide a interface
between unrelated classes and methods
What is inheritance, and why do you need it?
Ans: its is a method of the inheriting the properties of base
class into an another class. Its use ful when we need a class with
more functionality than the parent class. So we simply inherit the
base class to the new class. The new class has all the properties of
base class plus the the additional methods added in the new class
What is the Hollywood principle?
Ans: No idea
What is coupling?
Ans: its is described as how the one module is related to the the
other modules
What is tight coupling, is it bad or good?
Ans : if One module is heavily related to the the other modules is
referred as tight coupling . It is not good.
What are design patterns? What design patterns do you know,
which of them do you use?
Ans : No idea
What is the difference between equations of objects $a == $b and
$a === $b?
Ans : checks whether $a == $b equals, but the $a === $b is not only
checks equal, but also check its type.
What is the garbage collector? Describe the disadvantages of the garbage collector in PHP earlier than 5.3?
Ans : It is defined as the memory management, which reallocated the
resource's memory with no future usage.
Please give me the uncompleted answers though the comments
PHP Question and answers
Do you need to initialize the variable before its usage? Why?
Ans: Actually, Its not mandatory in php. But its recommended to
initialize variable before its usage. In most of the servers the the
error reporting for display notices are disabled. In the case of
servers which enabled error reporting on for notices, its highly
recommended to initialize variable before its usage.
How do you use a function's parameters inside the function?
Ans: Information are passed to the functions as parameters
separated by commas. We can handle these parameters in several ways.
We can pass variables into the function
We can pass arrays to the function
We can set default argument values in the function parameters.
There are two non-empty arrays $a and $b. What is the result of their sum (+) ?
Ans: it will return the value of $a (the first array);
Comment the following code: $q = 'SELECT * FROM mytable WHERE id = ' . $_POST['id'] ? Is there any possibility to make it better?
Ans: $q = 'SELECT * FROM mytable WHERE id = ' . htmlentities ( mysql_real_escape_string ( $_POST['id'] ) );
How do you swap the values of string variables $a and $b, without using a third variable?
Ans : $a = "content";
$b = "not a content";
list($a,$b) = array($b,$a);
echo "new a is - ". $a;
echo "
new b is - ".$b;
What way will you choose to sort the array of strings?
Ans: Will use asort() function.
What methods can you use to start a PHP block? Which is best,and why?
Ans: we can use tags
tags
<% %> tags
The best on is tag. Because its the default code block
of php. It works on all servers , no need to edit the php.ini settings
in the server. The other blocks are referred as short tags. Its server
specific, needs to edit in the php.ini settings to activate them.
Will be the value of $a after the execution of the following line of code: $a = include 'somefile.php'; ?
Ans: It will execute the script in it
Describe the advantages and disadvantages of the various ways of configuring a Web server to process PHP scripts.
Ans: Please post your the answer as comments below
What are the sessions. How is sessions data stored at the server?
Ans: Session is defined as the instance between when a user starts a
requests to a particular webserver and closing the requests to that
server.
These informations can stored server based on the session ids. We can
store these informations on the server in its local memory, files, or
in the databases.
Another Question regarding XML .
$dom = new DomDocument();
$dom->load('test.xml');
$xpath = new DomXPath($dom);
$nodes = $xpath->query(???????, $dom->documentElement);
echo $nodes->item(0)->getAttributeNode('bgcolor')->value
. "\n";
?>
What XPath query should go in the ?????? above to display the "bgcolor" attribute of the first "body" node in the XML document?
Please answer through the comments I will make it publish on blog..............
1.
Which of the following will NOT add john to the users array?
1. $users[] = 'john';
Successfully adds john to the array
2. array_add($users,’john’);
Fails stating Undefined Function array_add()
3. array_push($users,‘john’);
Successfully adds john to the array
4. $users ||= 'john';
Fails stating Syntax Error
2.
What’s the difference between sort(), assort() and ksort? Under what circumstances would you use each of these?
1. sort()
Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length - 1. This is used primarily on arrays where the indexes/keys do not matter.
2. assort()
The assort function does not exist, so I am going to assume it should have been typed asort().
asort()
Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.
3. ksort()
Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.
3.
What would the following code print to the browser? Why?
PLAIN TEXT
PHP:
1.
$num = 10;
2.
function multiply(){
3.
$num = $num * 10;
4.
}
5.
multiply();
6.
echo $num; // prints 10 to the screen
Since the function does not specify to use $num globally either by using global $num; or by $_GLOBALS['num'] instead of $num, the value remains 10.
4.
What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?
Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.
Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.
PLAIN TEXT
PHP:
1.
$myVariable = "its' value";
2.
Myfunction(&$myVariable); // Pass by Reference Example
So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.
5.
What functions can you use to add library code to the currently running script?
This is another question where the interpretation could completely hit or miss the question. My first thought was class libraries written in PHP, so include(), include_once(), require(), and require_once() came to mind. However, you can also include COM objects and .NET libraries. By utilizing the com_load and the dotnet_load respectively you can incorporate COM objects and .NET libraries into your PHP code, thus anytime you see "library code" in a question, make sure you remember these two functions.
6.
What is the difference between foo() & @foo()?
foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.
@foo() will mask any parse/syntax/thrown errors as it executes.
You will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query. However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.
7.
How do you debug a PHP application?
This isn't something I do often, as it is a pain in the butt to setup in Linux and I have tried numerous debuggers. However, I will point out one that has been getting quite a bit of attention lately.
PHP - Advanced PHP Debugger or PHP-APD. First you have to install it by running:
pear install apd
Once installed, start the trace by placing the following code at the beginning of your script:
apd_set_pprof_trace();
Then once you have executed your script, look at the log in apd.dumpdir.
You can even use the pprofp command to format the data as in:
pprofp -R /tmp/pprof.22141.0
For more information see http://us.php.net/manual/en/ref.apd.php
8.
What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?
The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false. Such functions would be strpos and strrpos.
I am having a hard time with the second portion, as I am able to come up with scenarios where '==' will be false and '===' would come out true, but it's hard to think of the opposite. So here is the example I came up with:
PLAIN TEXT
PHP:
1.
if (strpos("abc", "a") == true)
2.
{
3.
// this does not get hit, since "a" is in the 0 index position, it returns false.
4.
}
5.
6.
if (strpos("abc", "a") === true)
7.
{
8.
// this does get hit as the === ensures this is treated as non-boolean.
9.
}
9.
How would you declare a class named “myclass” with no methods or properties?
PLAIN TEXT
PHP:
1.
class myclass
2.
{
3.
}
10.
How would you create an object, which is an instance of “myclass”?
PLAIN TEXT
PHP:
1.
$obj = new myclass();
It doesn't get any easier than this.
11.
How do you access and set properties of a class from within the class?
You use the $this->PropertyName syntax.
PLAIN TEXT
PHP:
1.
class myclass
2.
{
3.
private $propertyName;
4.
5.
public function __construct()
6.
{
7.
$this->propertyName = "value";
8.
}
9.
}
12.
What is the difference between include, include_once? and require?
All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.
1. include()
The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
2. include_once()
include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
3. require()
Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.
13.
What function would you use to redirect the browser to a new page?
1. redir()
This is not a function in PHP, so it will fail with an error.
2. header()
This is the correct function, it allows you to write header data to direct the page to a new location. For example:
PLAIN TEXT
PHP:
1.
header("Location: http://www.search-this.com/");
3. location()
This is not a function in PHP, so it will fail with an error.
4. redirect()
This is not a function in PHP, so it will fail with an error.
14.
What function can you use to open a file for reading and writing?
1. fget()
This is not a function in PHP, so it will fail with an error.
2. file_open()
This is not a function in PHP, so it will fail with an error.
3. fopen()
This is the correct function, it allows you to open a file for reading and/or writing. In fact, you have a lot of options, check out php.net for more information.
4. open_file()
This is not a function in PHP, so it will fail with an error.
15.
What's the difference between mysql_fetch_row() and mysql_fetch_array()?
mysql_fetch_row() returns all of the columns in an array using a 0 based index. The first row would have the index of 0, the second would be 1, and so on. Now another MySQL function in PHP is mysql_fetch_assoc(), which is an associative array. Its' indexes are the column names. For example, if my query was returning 'first_name', 'last_name', 'email', my indexes in the array would be 'first_name', 'last_name', and 'email'. mysql_fetch_array() provides the output of mysql_fetch_assoc and mysql_fetch_row().
16.
What does the following code do? Explain what's going on there.
PLAIN TEXT
PHP:
1.
$date='08/26/2003';
2.
print ereg_replace("([0-9]+)/([0-9]+)/([0-9]+)","\\2/\\1/\\3",$date);
This code is reformatting the date from MM/DD/YYYY to DD/MM/YYYY. A good friend got me hooked on writing regular expressions like below, so it could be commented much better, granted this is a bit excessive for such a simple regular expression.
PLAIN TEXT
PHP:
1.
// Match 0-9 one or more times then a forward slash
2.
$regExpression = "([0-9]+)/";
3.
// Match 0-9 one or more times then another forward slash
4.
$regExpression .= "([0-9]+)/";
5.
// Match 0-9 one or more times yet again.
6.
$regExpression .= "([0-9]+)";
Now the \\2/\\1/\\3 denotes the parentheses matches. The first parenthesis matches the month, the second the day, and the third the year.
17.
Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?
First of all why would you write a regular expression when a PHP function already exists? See php.net's strip_tags function. However, considering this is an interview question, I would write it like so:
PLAIN TEXT
PHP:
1.
$stringOfText = "
This is a test
";
2.
$expression = "/<(.*?)>(.*?)<\/(.*?)>/";
3.
echo preg_replace($expression, "\\2", $stringOfText);
4.
5.
// It was suggested (by Fred) that /(<[^>]*>)/ would work too.
6.
$expression = "/(<[^>]*>)/";
7.
echo preg_replace($expression, "", $stringOfText);
18.
What's the difference between the way PHP and Perl distinguish between arrays and hashes?
This is why I tell everyone to, "pick the language for the job!" If you only write code in a single language how will you ever answer this question? The question is quite simple. In Perl, you are required to use the @ sign to start all array variable names, for example, @myArray. In PHP, you just continue to use the $ (dollar sign), for example, $myArray.
Now for hashes in Perl you must start the variable name with the % (percent sign), as in, %myHash. Whereas, in PHP you still use the $ (dollar sign), as in, $myHash.
19.
How can you get round the stateless nature of HTTP using PHP?
The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.
There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.
20.
What does the GD library do?
This is probably one of my favorite libraries, as it is built into PHP as of version 4.3.0 (I am very happy with myself, I didn't have to look up the version of PHP this was introduced on php.net). This library allows you to manipulate and display images of various extensions. More often than not, it is used to create thumbnail images. An alternative to GD is ImageMagick, however, unlike GD, this does not come built in to PHP and must be installed on the server by an Administrator.
21.
Name a few ways to output (print) a block of HTML code in PHP?
Well you can use any of the output statments in PHP, such as, print, echo, and printf. Most individuals use the echo statement as in:
PLAIN TEXT
PHP:
1.
echo "My string $variable";
However, you can also use it like so:
PLAIN TEXT
PHP:
1.
echo
2.
This text is written to the screen as output and this $variable is parsed too. If you wanted you can have HTML tags in here as well. The END; remarks must be on a line of its own, and can't contain any extra white space.
3.
END;
22.
Is PHP better than Perl? - Discuss.
Come on, let's not start a flame over such a trivial question. As I have stated many times before,
"Pick the language for the job, do not fit the job into a particular language."
Perl in my opinion is great for command line utilities, yes it can be used for the web as well, but its' real power can be really demonstrated through the command line. Likewise, PHP can be used on the command line too, but I personally feel it's more powerful on the web. It has a lot more functions built with the web in mind, whereas, Perl seems to have the console in mind.
Personally, I love both languages. I used Perl a lot in college and I used PHP and Java a lot in college. Unfortunately, my job requires me to use C#, but I spend countless hours at home working in PHP, Perl, Ruby (currently learning), and Java to keep my skills up to date. Many have asked me what happened to C and C++ and do they still fit into my applications from time to time. The answer is primarily 'No'. Lately all of my development work has been for the web and though C and C++ could be written for the web, they are hardly the language to use for such tasks. Pick the language for the job. If I needed a console application that was meant to show off the performance differences between a quick sort, bubble sort, and a merge sort, give me C/C++! If you want a Photo Gallery, give me PHP or C# (though I personally find .NET languages better for quick GUI applications than web).
I would like to take this time to challenge other companies to post their interview questions or feel free to email them to me at search-this [at] cpradio [dot] org. I will be glad to read through them, and write an article about them revealing their answers for everyone to learn.
Changed # to % for Perl Hashes - Thanks to MrSpooky for pointing that out, can't believe I forgot that!
Q1.Can we write windows like applications in PHP.
Ans : Yes using PHP-GTK on linux and WinBinder on windows.
Q2.What difference does it make when I declare variables with $ and $ in prefix.
Ans: $x = "Lion";
$$x = "Zebra";
echo $Lion;
would display "Zebra"
Use : creating runtime variables
Q3.What is the difference between strpos and stripos function
Ans: strpos is case sensitive search, and stripos is case insensitive search
Q4.What are the ways by which we can find out if a variable has been declared?
Ans: isset or empty language constructs
Q5.What is "global" and how to use it?
Ans: variables declared outside the functions can be used inside the function using global keyword
Q6.What is the difference between echo and print
Ans: echo can take more than one parameter for displaying.
print cannot take more than one
e.g
echo 'This', 'That' //is valid
print 'This', 'That' //is invalid
print returns 1 always.
echo cannot be used to return anything
$ret = print "Abcd" //valid
$ret = echo "Abcd" //invalid
Q14.What does function `eval` do?
Ans: Evaluate a string as PHP code;
Eg. eval('echo "This would be printed"');
Q15.What is the method by which PHP converts datatype of a given variable.
Ans: settype()
$a = "10"; // $a is string
settype($a,"integer"); // $a is integer
Q.Can we change php.ini settings at the runtime, and how?
Ans : Yes, using ini_set();
Q16.What is the difference between sort(), assort() and ksort? Under what circumstances would you use each of these?
Ans: Sorts an array, sorts an array and maintains index association, Sorts an array by key
Simple sort (sorts on values)
Simple sort after sorting the array (lets assume size of array is 10) rearranges the index, if we want to access element at index[5], using a simple sort an element value would have changed, but in assort the value is still held by index 5 though its position in the array may be 10th.
Ksort – sorts the array by key and maintains the key to data correlations
Q17.What is the difference between foo() & @foo()?
Ans: if an error occurs calling foo() would show up the error on the screen, whereas, @foo() would suppress the error because ‘@’ is a error control operator.
Q18.What is the difference between mysql_fetch_row() and mysql_fetch_array() and mysql_fetch_object?
Ans: mysql_fetch_row() – fetches a row as an enumerated array
mysql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_object - Fetch a result row as an object
Q19.What is the difference between include & include_once? include & require?
Ans: include_once includes the script only once if it is already included in the execution of the script
Include includes the script everytime the include is encountered in the code
Require is identical to include except that it results in fatal error when file is not present in the include_path.
Q20.What type of inheritance PHP supports?
Ans: An object can inherit only from one base class. Multiple inheritance is not supported in PHP.
Q21.How can we call an object's method by using the variable functions?
Ans: If MyClass contains function myFunction()
…
$foo = new MyClass();
$var = "myFunction";
$c->$var();
[ Resource Link : http://in.php.net/manual/en/functions.variable-functions.php ]
Ajax, Cross site scripting (JavaScript).
Q22.What is the use of AJAX?
Ans: If a page contains form that needs to be updated constantly based on runtime values, a javascript code constantly sends user input to the system and displays the results from the server, without refreshing the whole page.
Q23.What is cross site scripting, and how to avoid it?
Ans: Injecting a javascript code in the response of a form that is capable of calling and executing scripts from other site.
Occurs when variables holding form values are not cleaned with html code escaping functions.
Clean the variables before storing or before display. Recommendation is to display the code clean and store the value as it is, unless its specified otherwise.
Q1.What is a join, what types of join are supported in MySQL.
Ans: A ‘join’ joins two table in such a way that all or partial records are selected from both the table based on join criteria.
Joins supported in mysql are :
[INNER | CROSS] JOIN
STRAIGHT_JOIN
LEFT [OUTER] JOIN
NATURAL [LEFT [OUTER]] JOIN
RIGHT [OUTER] JOIN
NATURAL [RIGHT [OUTER]] JOIN
Q2.In MySQL, what table type is required for foreign keys to work?
Ans: innoDB
Q3.How does full text search work.
Ans: A table must be a myISAM table
Table must have char varchar and text columns
FULLTEXT index must be created at the time of creation of table
Q4.What is the use of files .frm, .MYD, .MYI
Ans: frm files store the table definition
MYD files store the data
MYI files store the index
Q5.What is maximum size of a database in MySQL?
Ans: 65+GB / table / [ limited by the OS]
Q6.How many columns can exist in a mySql table?
Ans: 4096 colums
Q7.What is the maximum size of a row in a mysql table?
Ans: 65,535 not including blobs (as these are stored separately)
Q8. What would you use if you have a choice Natural [left] join or inner join or left join with using clause?
Ans: The NATURAL [LEFT] JOIN of two tables is defined to be semantically
equivalent to an INNER JOIN or a LEFT JOIN with a USING clause that names all columns that exist in both tables
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?
Ans :-
In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.
2. Who is the father of php and explain the changes in php versions?
Ans :-
Rasmus Lerdorf for version changes goto http://php.net/
3. How can we submit from without a submit button?
Ans:-
Trigger the JavaScript code on any event ( like onselect of drop down list box, onfocus, etc ) document.myform.submit();This will submit the form.
4. How many ways we can retrieve the date in result set of mysql using php?
Ans:-
As individual objects so single record or as a set or arrays.
5. What is the difference between mysql_fetch_object and mysql_fetch_array?
Ans:-
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array
6. What is the difference between $message and $$message?
Ans:-
Both are variables only
$message is a variable and if used with print statement, the content of the $message variable will be displayed. Where as with $$message variable, the content of the $message will also be treated as variable and the content of that variable will be displayed. For ex: If $message contains "var", then it displays the content of $var on the screen.
7. How can we extract string 'abc.com ' from a string 'http://info@abc.com' using regular _expression of php?
Ans:-
preg_match("/^(http:\/\/info@)?([^\/]+)/i","http://info@abc.com", $data);
echo $data[2];
Use the function split split(“@”,”http://info@abc.com”) which returns an array any second element of the returned array will hold the value as abc.com.
8. How can we create a database using php and mysql?
Ans:-
mysql_create_db()
9. What are the differences between require and include, include_once?
Ans:-
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(). This will prevent problems with function redefinitions, variable value reassignments, etc.
10. Can we use include ("abc.php") two times in a php page "makeit.php"?
Ans:-
Yes we can include..
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)) ?
Ans:-
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.
Table Types are
· ISAM(Index Sequential Access Method)
· MyISAM
o Static
o Dynamic
o Compress
· Merge
· Heap (Fastest tables because it stores in to the RAM)
· BDB
· InnoDB (Transaction safe table)
When you fire the above create query MySQL will create the Dynamic table.
http://dev.mysql.com/doc/mysql/en/storage-engines.html
MyISAM Table Type is created, if u not specified any table type then default will be applied and MyISAM is default
13. How can I execute a PHP script using command line?
Ans:-
Through php parse you can execute PHP script using command line. By default location of php parser is /var/www/html so set the path of this directory and just use as following
#php sample.php
16. What is meant by nl2br()?
Ans:-
nl2br() inserts html break in string
echo nl2br(”god bless \n you”);
output--
god bless
you
Returns string with ‘’ inserted before all newlines
20. How can we encrypt and decrypt a data present in a mysql table using mysql?
Ans:-
AES_ENCRYPT() and AES_DECRYPT() ---to encrypt string
21. How can we encrypt the username and password using PHP?
Ans:-
You can encrypt a password with the following
Mysql>SET PASSWORD=PASSWORD("Password");
26. What are the different types of errors in PHP?
Ans:-
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.
27. What is the functionality of the function strstr and stristr?
Ans:-
string strstr ( string str1, string str2) this function search the string str1 for the first occurrence of the string str2 and returns the part of the string str1 from the first occurrence of the string str2. This function is case-sensitive and for case-insensitive search use stristr() function.
28. What are the differences between PHP 3 and PHP 4 and PHP 5?
Ans:-
for this ans goto http://php.net and check the version changes
29. How can we convert asp pages to PHP pages?
Ans:-
You can download asp2php front end application from the site http://asp2php.naken.cc.
30. What is meant by urlencode and urldecode?
Ans:-
string urlencode(str)
where str contains a string like this "hello world" and the return value will be URL encoded and can be use to append with URLs, normaly used to appned data for GET like someurl.com?var=hello%world
string urldocode(str)
this will simple decode the GET variable’s value
Like it echo (urldecode($_GET_VARS[var])) will output "Hello world"
34. What is the difference between the functions unlink and unset?
Ans:-
unlink is a function for file system handling. It will simply delete the file in context
unset will set UNSET the variable. e.g
35. How can we register the variables into a session?
Ans:-
Yes we can
session_register($ur_session_var);
42. How many ways can we get the value of current session id?
ans:-
session_id() returns the session id for the current session.
43. How can we destroy the session, how can we unset the variable of a session?
Ans:-
session_unregister -- Unregister a global variable from the current session
session_unset -- Free all session variables
44. How can we destroy the cookie?
Ans:-
Set the cookie in past
45. How many ways we can pass the variable through the navigation between the pages?
Ans:-
GET or QueryString and POST
46. What is the difference between ereg_replace() and eregi_replace()?
Ans:-
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.
47. What are the different functions in sorting an array?
Ans:-
Sorting functions in PHP,
asort-http://www.php.net/manual/en/function.asort.php
arsort-http://www.php.net/manual/en/function.arsort.php
ksort-http://www.php.net/manual/en/function.ksort.php
krsort-http://www.php.net/manual/en/function.krsort.php
uksort-http://www.php.net/manual/en/function.uksort.php
sort-http://www.php.net/manual/en/function.sort.php
natsort-http://www.php.net/manual/en/function.natsort.php
rsort-http://www.php.net/manual/en/function.rsort.php
48. How can we know the count/number of elements of an array?
Ans:-
2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
interestingly if u just pass a simple var instead of a an array it will return 1.
53. List out the predefined classes in PHP?
Ans:-
1. Standard Defined Classes
These classes are defined in the standard set of functions included in the PHP build.
a. Directory
The class from which dir() is instantiated.
b.stdClass
2.Ming Defined Classes
These classes are defined in the Ming extension, and will only be available when that
extension has either been compiled into PHP or dynamically loaded at runtime.
a.swfshape
b. swffill
c. swfgradient
d. swfbitmap
e. swftext
f. swftextfield
g. swffont
h. swfdisplayitem
i. swfmovie
j. swfbutton
k. swfaction
l. swfmorph
m. swfsprite
3. Oracle 8 Defined Classes
These classes are defined in the Oracle 8 extension, and will only be available when
that extension has either been compiled into PHP or dynamically loaded at runtime.
a. OCI-Lob
b. OCI-Collection
4. qtdom Defined Classes
These classes are defined in the qtdom extension, and will only be available when that
extension has either been compiled into PHP or dynamically loaded at runtime.
a. QDomDocument
b. QDomNode
56. How can we send mail using JavaScript?
Ans:-
No You can't send mail using Javascript but u can execute a client side email client to send the email using mailto: code.
Using clientside email client
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location="mailto:mailid@domain.com?subject="+tdata+"/MYFORM";
return true;
}
This question is wrong. You aren’t really ’sending mail’ when doing a ‘mailto’ and so it’s a misleading question… A smart candidate would just say “It’s not possible” and you may write him off.
57. What is meant by PEAR in php?
Ans:-
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"
58. What is the purpose of the following files having extensions 1) frm 2) MYD 3) MYI. What these files contains?
Ans:-
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,
59.Session
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
60. What is the difference between echo and print statement?
echo() can take multiple expressions,Print cannot take multiple expressions.
echo has the slight performance advantage because it doesn't have a return value.
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.
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.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.
What is meant by PEAR in php?
Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"
Answer2:
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.
How can we know the number of days between two given dates using PHP?
Simple arithmetic:
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
How can we repair a MySQL table?
The syntex for repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.
What is the difference between $message and $$message?
Anwser 1:
$message is a simple variable whereas $$message is a reference variable. Example:
$user = 'bob'
is equivalent to
$holder = 'user';
$$holder = 'bob';
Anwser 2:
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.
What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
Temporary cookies can not be used for tracking long-term information.
Persistent cookies can be used for tracking long-term information.
Temporary cookies are safer because no programs other than the browser can access them.
-
Persistent cookies are less secure because users can open cookie files see the cookie values.
What does a special set of tags do in PHP?
The output is displayed directly to the browser.
How do you define a constant?
Via define() directive, like define ("MYCONSTANT", 100);
How To Write the FORM Tag Correctly for Uploading Files?
When users clicks the submit button, files specified in the will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written
Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data" in order for the uploading process to work. The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:
print("
." method=post enctype=multipart/form-data>\n");
print("Please submit an image file a Web site logo for"
." fyicenter.com:
\n");
print("
\n");
print("\n");
print("\n");
?>
What are the differences between require and include, include_once?
Answer 1:
require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
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. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
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. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.
Anwser 4:
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(). This will prevent problems with function redefinitions, variable value reassignments, etc.
What is meant by urlencode and urldecode?
Anwser 1:
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.
Anwser 2:
string urlencode(str) - Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
Alphanumeric characters are maintained as is.
Space characters are converted to "+" characters.
Other non-alphanumeric characters are converted "%" followed by two hex digits representing the converted character.
string urldecode(str) - Returns the original string of the input URL encoded string.
For example:
$discount ="10.00%";
$url = "http://domain.com/submit.php?disc=".urlencode($discount);
echo $url;
You will get "http://domain.com/submit.php?disc=10%2E00%25".
How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. 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.
The $fieldName is the name used in the .
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
How can I execute a PHP script using command line?
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.
I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.
Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?
In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.
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))?
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. When you fire the above create query MySQL will create a MyISAM table.
How To Create a Table?
If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:
include "mysql_connection.php";
$sql = "CREATE TABLE fyi_links ("
. " id INTEGER NOT NULL"
. ", url VARCHAR(80) NOT NULL"
. ", notes VARCHAR(1024)"
. ", counts INTEGER"
. ", time TIMESTAMP DEFAULT sysdate()"
. ")";
if (mysql_query($sql, $con)) {
print("Table fyi_links created.\n");
} else {
print("Table creation failed.\n");
}
mysql_close($con);
?>
Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:
Table fyi_links created.
How can we encrypt the username and password using PHP?
Answer1
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");
Answer2
You can use the MySQL PASSWORD() function to encrypt username and password. For example,
INSERT into user (password, ...) VALUES (PASSWORD($password”)), ...);
How do you pass a variable by value?
Just like in C++, put an ampersand in front of it, like $a = &$b
WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()?
string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.
stristr() is idential to strstr() except that it is case insensitive.
When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.
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;
}
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.
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.
How do I find out the number of parameters passed into function9. ?
func_num_args() function returns the number of parameters passed in.
What is the purpose of the following files having extensions: frm, myd, and myi? What these files contain?
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,
If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
100, it’s a reference to existing variable.
Write a query for the following question
The table tbl_sites contains the following data:
-----------------------------------------------------
Userid sitename country
------------------------------------------------------
1 sureshbabu indian
2 PHPprogrammer andhra
3 PHP.net usa
4 PHPtalk.com germany
5 MySQL.com usa
6 sureshbabu canada
7 PHPbuddy.com pakistan
8. PHPtalk.com austria
9. PHPfreaks.com sourthafrica
10. PHPsupport.net russia
11. sureshbabu australia
12. sureshbabu nepal
13. PHPtalk.com italy
Write a select query that will be displayed the duplicated site name and how many times it is duplicated? …
SELECT sitename, COUNT(*) AS NumOccurrences
FROM tbl_sites
GROUP BY sitename HAVING COUNT(*) > 1
How To Protect Special Characters in Query String?
If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode(): Please click the links below"
");
print("
." to submit comments about FYICenter.com:
$comment = 'I want to say: "It\'s a good site! :->"';
$comment = urlencode($comment);
print("");
$comment = 'This visitor said: "It\'s an average site! :-("';
$comment = urlencode($comment);
print("");
print("");
?>
Are objects passed by value or by reference?
Everything is passed by value.
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.
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?
Anwser 1:
When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn't display these values.
Anwser 2:
When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method.
Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information.
Anwser 3:
What are "GET" and "POST"?
GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as "standard input."
Major Difference
In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.
Ex: Assume we are logging in with username and password.
GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=...&password=... as URL when executing the script login.php) and is retrieved by login.php by $_GET['username'] and $_GET['password'].
POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST['username'] and $_POST['password'].
POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).
Anwser 4:
In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.
Anwser 5:
When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn't display value with URL. It passes value in the form of Object and we can submit large data from the form.
Anwser 6:
On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.
On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.
GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.
How do you call a constructor for a parent class?
parent::constructor($value)
WHAT ARE THE DIFFERENT TYPES OF ERRORS 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
What’s the special meaning of __sleep and __wakeup?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
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. For example:
Submit Me
Why doesn’t the following code print the newline properly?
Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters - \ and n.
Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.
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",$data);
echo $data[1];
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.
How come the code works, but doesn’t for two-dimensional array of mine?
Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked.
How can we register the variables into a session?
session_register($session_var);
$_SESSION['var'] = 'value';
What is the difference between characters \023 and \x23?
The first one is octal 23, the second is hex 23.
With a heredoc syntax, do I get variable substitution inside the heredoc contents?
Yes.
How can we submit form 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. For example:
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.
How many ways we can retrieve the date in result set of mysql using php?
As individual objects so single record or as a set or arrays.
Can we use include ("abc.php") two times in a php page "makeit.php"?
Yes.
For printing out strings, there are echo, print and printf. Explain the differences.
echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:
and it will output the string "Welcome to fyicenter!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.
I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?
On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().
What’s the output of the ucwords function in this example?
$formatted = ucwords("FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS");
print $formatted;
What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS.
ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.
What’s the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
How can we extract string "abc.com" from a string "mailto:info@abc.com?subject=Feedback" using regular expression of PHP?
$text = "mailto:info@abc.com?subject=Feedback";
preg_match('|.*@([^?]*)|', $text, $output);
echo $output[1];
Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].
So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?
Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.
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
What are the different functions in sorting an array?
Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
How can we know the count/number of elements of an array?
2 ways:
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.
How many ways we can pass the variable through the navigation between the pages?
At least 3 ways:
1. Put the variable into session in the first page, and get it back from session in the next page.
2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
3. Put the variable into a hidden form field, and get it back from the form in the next page.
What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters
Table name: 64 characters
Column name: 64 characters
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.
What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?
DESCRIBE table_name;
How can we find the number of rows in a table using MySQL?
Use this for MySQL
SELECT COUNT(*) FROM table_name;
What’s the difference between md5(), crc32() and sha1() crypto on PHP?
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
How can we find the number of rows in a result set using PHP?
Here is how can you find the number of rows in a result set in PHP:
$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
Give the syntax of GRANT commands?
The generic syntax for GRANT is as following
GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.
What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters
Table name: 64 characters
Column name: 64 characters
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.
What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?
DESCRIBE table_name;
How can we find the number of rows in a table using MySQL?
Use this for MySQL
SELECT COUNT(*) FROM table_name;
What’s the difference between md5(), crc32() and sha1() crypto on PHP?
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
How can we find the number of rows in a result set using PHP?
Here is how can you find the number of rows in a result set in PHP:
$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
Give the syntax of GRANT commands?
The generic syntax for GRANT is as following
GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.
Give the syntax of REVOKE commands?
The generic syntax for revoke is as following
REVOKE [rights] on [database] FROM [username@hostname]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.
Answer the questions with the following assumption
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 of the last row is 2345. What will happen in the following conditions?
Condition 1: Delete all the rows and insert another row. What is the starting value for this auto incremented field user_pri_id?
Condition 2: Delete the last row (having the field value 2345) and insert another row. What is the value for this auto incremented field user_pri_id?
In both conditions, the value of this auto incremented field user_pri_id is 2346.
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.
How can we encrypt and decrypt a data present in a mysql table using mysql?
AES_ENCRYPT() and AES_DECRYPT()
Will comparison of string "10" and integer 11 work in PHP?
Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
Popular Posts
- Elgg : The most popular open source social networking platform
- function to check whether the year given is a leap year or not
- How to create a plugin in elgg.
- some php questions
- Mysql optimization by configuring the query cache
- Pattern Matching in mysql
- php Questions
- creating dynamic elements in HTML using Javascript.
- php questions
- Jquery based dynamic adding and removal of html elements.