* Regular Expressions interview questions
Top Regular Expressions interview questions and answers
| Questions : 1 | What is the mean of Regular Expressions ? What the use of Regular Expressions ? | |
| Answers : 1 | Regular Expressions means we can say a pattern that one is an expression thatspecifies a set of strings. And there are lot of great use of these expressions like
|
|
| Questions : 2 | What the mean of different symbols like ^, $, * , + , ?, ., {},[]in Regular Expressions | |
| Answers : 2 | These symbols ^, $, * , + , ?, ., {},[] are very usefull like
|
|
| Questions : 3 | How we list which characters we DON’T want ?How to use backslash character | |
| Answer : 3 | We can list which characters we DON’T want so just use a ‘^’ as the first symbol in a bracket expression(i.e., “%[^a-zA-Z]%” matches a string with a character that is not a letter between two percent signs).
“^[a-zA-Z]“: a string that starts with a letter; “[0-9]%”: a string that has a single digit before a percent sign; “,[a-zA-Z0-9]$”: a string that ends in a comma followed by an alphanumeric character.In order to be taken literally, you must escape the characters “^.[$()|*+?{\" with a backslash ('\'), as they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression "(\$|¥)[0-9]+” would have the function call: ereg(“(\\$|¥)[0-9]+”, $str) |
|
| Questions : 4 | How you can validate email id use REG expression | |
| Answer : 4 | By using below reg expression we can validate email id^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$“^[_a-z0-9-]+”: start with any underscore or alphanumeric one or more then one alfanumaric word
“(\.[_a-z0-9-]+)*@”:any dot(.) or alphanumeric zero times or more the zero and a @ sign “[a-z0-9-]+”:one or more alphanumeric “(\.[a-z0-9-]+)*”: zero or more dot alphanumeric or -(mins sign) “(\.[a-z]{2,5})$”: End with two to 5 character may use dot (.) in that |
* Php Objective Questions with Answers
Php Objective Questions with Answers for written test exams all
Question 1
What will the following script output?
<?php
$x = 3 – 5 % 3;
echo $x;
?>
A. 2
B. 1
C. Null
D. True
E. 3
Answer B is correct. Because of operator precedence, the modulus operation is
performed first, yielding a result of 2 (the remainder of the division of 5 by 2).
Then, the result of this operation is subtracted from the integer 3.
Question 2
Which data type will the $a variable have at the end of the following script?
<?php
$a = “1”;
echo $x;
?>
A. (int) 1
B. (string) “1”
C. (bool) True
D. (float) 1.0
E. (float) 1
Answer B is correct.When a numeric string is assigned to a variable, it remains
a string, and it is not converted until needed because of an operation that
requires so.
Question 3
What will the following script output?
<?php
$a = 1;
$a = $a— + 1;
echo $a;
?>
A. 2
B. 1
C. 3
D. 0
E. Null
Answer A is correct.The expression $a— will be evaluated after the expression $a
= $a + 1 but before the assignment.Therefore, by the time $a + 1 is assigned to
$a, the increment will simply be lost.
Question 4
What will the following script output?
<?php
class a
{
var $c;
function a ($pass)
{
$this->c = $pass;
}
function print_data()
{
echo $this->$c;
}
}
$a = new a(10);
$a->print_data();
?>
A. An error
B. 10
C. “10”
D. Nothing
E. A warning
Answer D is correct.There actually is a bug in the print_data() function—
$this->$c is interpreted as a variable by PHP, and because the $c variable is not
defined inside the function, no information will be available for printing. Note
that if error reporting had been turned on, either through a php.ini setting or
through an explicit call to error_reporting(), two warnings would have been
outputted instead—but, unless the exam question tells you otherwise, you should
assume that the normal PHP configuration is being used. And in that case, the
interpreter is set not to report warnings.
Question 5
When serializing and unserializing an object, which of the following precautions
should you keep in mind? (Choose two)
A. Always escape member properties that contain user input.
B. If the object contains resource variables, use magic functions to restore the
resources upon unserialization.
C. Use the magic functions to only save what is necessary.
D. Always use a transaction when saving the information to a database.
E. If the object contains resource variables, it cannot be serialized without first
destroying and releasing its resources.
Answers B and C are correct.Whenever you design an object that is meant to be
serialized or that can contain resource objects, you should implement the appropriate
magic functions to ensure that it is serialized and unserialized properly—and
using the smallest amount of information possible.
Question 6
What will the following script output?
<?php
error_reporting(E_ALL);
class a
{
var $c;
function a()
{
$this->c = 10;
}
}
class b extends a
{
function print_a()
{
echo $this->c;
}
}
$b = new b;
$b->print_a();
?>
A. Nothing
B. An error because b does not have a constructor
C. 10
D. NULL
E. False
Answer C is correct. Because the class b does not have a constructor, the constructor
of its parent class is executed instead.This results in the value 10 being assigned
to the $c member property
Question 7
Is it possible to pass data from PHP to JavaScript?
A. No, because PHP is server-side, and JavaScript is client-side.
B. No, because PHP is a loosely typed language.
C. Yes, because JavaScript executes before PHP.
D. Yes, because PHP can generate valid JavaScript
Answer D is correct. JavaScript, like HTML, can be dynamically generated by
PHP. Answers A and B are incorrect because the answer is yes. Answer C is incorrect
because PHP executes before JavaScript.
Question 8
Is it possible to pass data from JavaScript to PHP?
A. Yes, but not without sending another HTTP request.
B. Yes, because PHP executes before JavaScript.
C. No, because JavaScript is server-side, and PHP is client-side.
D. No, because JavaScript executes before PHP.
Answer A is correct. Although your instincts might lead you to believe that you
cannot pass data from JavaScript to PHP, such a thing can be achieved with another
HTTP request. Answer B is incorrect because PHP executing before JavaScript
is not what makes this possible.This is actually the characteristic that might lead
you to believe (incorrectly) that the answer is no. Answers C and D are incorrect
because the answer is yes, but also because the explanations given are false.
Question 9
Which types of form elements can be excluded from the HTTP request?
A. text, radio, and check box
B. text, submit, and hidden
C. submit and hidden
D. radio and check box
Answer D is correct.When not selected, both radio buttons and check boxes are
excluded from the HTTP request. Answer A and B are incorrect because text
boxes are always included in the request. Answer C is incorrect because hidden
form elements are always included.
Question 10
When processing the form, what is the difference between a hidden form element
and a nonhidden one, such as a text box?
A. The hidden form element does not have a name.
B. There is no difference.
C. The hidden form element does not have a value.
D. The hidden form element is excluded from the request.
Answer B is correct.When processing a form, each form element is simply a
name/value pair within one of the superglobal arrays. Answers A and C are incorrect
because hidden form elements can (and should) have both a name and a
value. Answer D is incorrect because hidden form elements are only excluded
from the user’s view, not from the HTTP request.
Question 11
Which of the following form element names can be used to create an array in
PHP?
A. foo
B. [foo]
C. foo[]
D. foo[bar]
Answer C is correct. PHP will create an enumerated array called foo that contains
the values of all form elements named foo[] in the HTML form.Answers A, B,
and D are incorrect because any subsequent form elements of the same name will
overwrite the value in previous elements.
Question 12
When an expiration date is given in a Set-Cookie header, what is the resulting
behavior in subsequent requests?
A. If the expiration date has expired, the cookie is not included.
B. The behavior is the same; the expiration date is included in the Cookie
header, and you can access this information in the $_COOKIE superglobal
array.
C. The cookie persists in memory until the browser is closed.
D. The cookie is deleted and therefore not included in subsequent requests.
Answer A is correct. Answer B is incorrect because only the name and value of the
cookie are included in the Cookie header. Answer C is incorrect because setting
an expiration date causes a cookie to either be deleted (if the date has expired) or
written to disk. Answer D is incorrect because the cookie is only deleted if the
date has expired, which isn’t necessarily the case.
Question 13
If you set a cookie with either setcookie() or header(), you can immediately
check to see whether the client accepted it.
A. True, you can check the $_COOKIE superglobal array to see if it contains the
value you set.
B. True, but only if register_globals is enabled.
C. False, you can only use setcookie() if you need to test for acceptance.
Using header() does not work.
D. False, you must wait until you receive another HTTP request to determine
whether it includes the Cookie header.
Answer D is correct.The response that contains the Set-Cookie header is not sent
until PHP finishes executing, so you cannot test for acceptance prior to this.
Answers A and B are incorrect because the answer is false. Answer C is incorrect
because using setcookie() and header() both result in the same thing: A Set-
Cookie header is included in the response.
Question 14
Why must you call session_start() prior to any output?
A. Because it is easy to forget if not placed at the top of your scripts.
B. Because you can no longer access the session data store after there has been
output.
C. Because session_start() sets some HTTP headers.
D. Because calling session_start() causes the HTTP headers to be sent.
Answer C is correct. Answer A is incorrect because this is a technical necessity, not
a best practice. Answer B is incorrect because accessing the session data store is
completely independent of whether there has been any output. Answer D is incorrect
because you can set other HTTP headers after a call to session_start().
Question 15
Which of the following represents the proper way to set a session variable?
A. $_SESSION[‘foo’] = ‘bar’;
B. session_start();
C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,
‘mywrite’, ‘mydelete’, ‘mygarbage’);
D. $foo = $_SESSION[‘foo’];
Answer A is correct. Answer B is incorrect because session_start() only activates
PHP sessions for the current script. Answer C is incorrect because
session_set_save_handler() allows you to override PHP’s default session
mechanism with your own custom functions. Answer D is incorrect; session data is
being used as the value of a regular variable and is not being manipulated in any
way.
Question 16
Which of the following functions allows you to store session data in a database?
A. session_start();
B. session_set_save_handler();
C. mysql_query();
D. You cannot store session data in a database.
Answer B is correct.You can use session_set_save_handler() to override
PHP’s default session-handling functions and store session data any way you want.
Answer A is incorrect because session_start() only activates PHP sessions for
the current script. Answer C is incorrect because mysql_query() only executes a
query with MySQL and does not affect the behavior of PHP’s session mechanism.
Answer D is incorrect because this statement is false
Question 17
Which of the following types can be used as an array key? (Select three.)
A. Integer
B. Floating-point
C. Array
D. Object
E. Boolean
Answers A, B, and E are correct. A Boolean value will be converted to either 0 if
it is false or 1 if it is true, whereas a floating-point value will be truncated to its
integer equivalent.Arrays and objects, however, cannot be used under any circumstance.
Question 18
Which of the following functions can be used to sort an array by its keys in
descending order?
A. sort
B. rsort
C. ksort
D. krsort
E. reverse_sort
Answer D is correct.The sort() and rsort() functions operate on values, whereas
ksort() sorts in ascending order and reverse_sort() is not a PHP function.
Question 19
What will the following script output?
<?php
$a = array (‘a’ => 20, 1 => 36, 40);
array_rand ($a);
echo $a[0];
?>
A. A random value from $a
B. ‘a’
C. 20
D. 36
E. Nothing
ANSWER E Only E is correct.The $a array doesn’t have any element with a numeric key of
zero, and the array_rand() function does not change the keys of the array’s elements—
only their order.
Question 20
Given
$email = ‘bob@example.com’;
which code block will output example.com?
A. print substr($email, -1 * strrpos($email, ‘@’));
B. print substr($email, strrpos($email, ‘@’));
C. print substr($email, strpos($email, ‘@’) + 1);
D. print strstr($email, ‘@’);
Answer C is correct. strpos() identifies the position of the @ character in the
string.To capture only the domain part of the address, you must advance one place
to the first character after the @.
Question 21
Which question will replace markup such as img=/smiley.png with <img
src=”/smiley.png”>?
A. print preg_replace(‘/img=(\w+)/’, ‘<img src=”\1”>’, $text);
B. print preg_replace(‘/img=(\S+)/’, ‘<img src=”\1”>’, $text);
C. print preg_replace(‘/img=(\s+)/’, ‘<img src=”\1”>’, $text);
D. print preg_replace(‘/img=(\w)+/’, ‘<img src=”\1”>’, $text);
Answer B is correct.The characters / and . are not matched by \w (which only
matches alphanumerics and underscores), or by \s (which only matches whitespace).
Question 22
Which of the following functions is most efficient for substituting fixed patterns in
strings?
A. preg_replace()
B. str_replace()
C. str_ireplace()
D. substr_replace()
Answer B is correct.The PHP efficiency mantra is “do no more work than necessary.”
Both str_ireplace() and preg_replace() have more expensive (and flexible)
matching logic, so you should only use them when your problem requires it.
substr_replace() requires you to know the offsets and lengths of the substrings
you want to replace, and is not sufficient to handle the task at hand.
Question 23
If
$time = ‘Monday at 12:33 PM’;
or
$time = ‘Friday the 12th at 2:07 AM’;
which code fragment outputs the hour (12 or 2, respectively)?
A. preg_match(‘/\S(\d+):/’, $time, $matches);
print $matches[1];
B. preg_match(‘/(\w+)\Sat\S(\d+):\d+/’, $time, $matches);
print $matches[2];
C. preg_match(‘/\s([a-zA-Z]+)\s(\w+)\s(\d+):\d+/’, $time,
$matches);
print $matches[3];
D. preg_match(‘/\s(\d+)/’, $time, $matches);
print $matches[1];
E. preg_match(‘/\w+\s(\d+):\d+/’, $time, $matches);
print $matches[1];
Answer E is correct. Answer A and B both fail because \S matches nonwhitespace
characters, which break the match. Answer C will correctly match the first $time
correctly, but fail on the second because ‘12th’ will not match [a-zA-Z]. Answer D
matches the first, but will fail on the second, capturing the date (12) instead of the
hour.
Question 24
Which of the following output ‘True’?
A. if(“true”) { print “True”; }
B. $string = “true”;
if($string == 0) { print “True”; }
C. $string = “true”;
if(strncasecmp($string, “Trudeau”, 4)) { print “True”; }
D. if(strpos(“truelove”, “true”)) { print “True”; }
E. if(strstr(“truelove”, “true”)) { print “True”; }
Answers A, B, C, and E are correct. Answer A is correct because a non-empty
string will evaluate to true inside an if() block. Answer B is covered in the chapter—
when comparing a string and an integer with ==, PHP will convert the string
into an integer. ‘true’ converts to 0, as it has no numeric parts. In answer C,
strncasecmp() returns 1 because the first four characters of ‘Trud’ come before
the first four characters of true when sorted not case sensitively. Answer D is
incorrect because strpos() returns 0 here (true matches truelove at offset 0).
We could make this return True by requiring strpos() to be !== false. Answer
E is correct because strstr() will return the entire string, which will evaluate to
true in the if() block.
Question 25
What are the contents of output.txt after the following code snippet is run?
<?php
$str = ‘abcdefghijklmnop’;
$fp = fopen(“output.txt”, ‘w’);
for($i=0; $i< 4; $i++) {
fwrite($fp, $str, $i);
}
?>
A. abcd
B. aababcabcd
C. aababc
D. aaaa
The correct answer is C. On the first iteration, $i is 0, so no data is written. On
the second iteration $i is 1, so a is written. On the third, ab is written, and on the
fourth abc is written.Taken together, these are aababc.
Question 26
Which of the following can be used to determine if a file is readable?
A. stat()
B. is_readable()
C. filetype()
D. fileowner()
E. finfo()
The correct answers are A and B. stat() returns an array of information about a
file, including who owns it and what its permission mode is.Together these are
sufficient to tell if a file is readable. is_readable(), as the name implies, returns
true if a file is readable.
Question 27
Specifying the LOCK_NB flag to flock() instructs PHP to
A. Return immediately if someone else is holding the lock.
B. Block indefinitely until the lock is available.
C. Block for a number of seconds dictated by the php.ini setting
flock.max_wait or until the lock is available.
D. Immediately take control of the lock from its current holder.
The correct answer is A.The LOCK_NB flag instructs PHP to take a nonblocking
lock, which immediately fails if another process holds the lock.
Question
28
If you have an open file resource, you can read data from it one line at a time with
the _____ function.
The correct answer is fgets().
Question 29
Which of the following functions require an open file resource?
A. fgets()
B. fopen()
C. filemtime()
D. rewind()
E. reset()
The correct answers are A and D. fgets() and rewind() both act on an open file
resource. fopen() opens files to create resources, whereas filemtime() takes a filename
and reset() acts on arrays.
Question 30
Which of the following sentences are incorrect?
A. date() returns the current UNIX datestamp.
B. date() returns a formatted date string.
C. date() requires a time stamp to be passed to it.
D. date() returns a date array.
The correct answers are A, C, and D. date() takes a format string and an optional
time stamp and produces a formatted date string. If a UNIX time stamp is not
passed into date(), it will use the current time.
Question 31
The ________ function will return the current UNIX time stamp.
The correct answer is time().
Question
32
Which of the following functions will output the current time as 11:26 pm?
A. print date(‘H:m a’);
B. print date(‘G:M a’);
C. print date(‘G:i a’);
D. print strftime(‘%I:%M %p’);
The correct answers are C and D.
Question 33
The PHP date functions are only guaranteed to work for dates after _____.
A. January 1, 1970 00:00:00
B. January 1, 1900 00:00:00
C. January 1, 1963 00:00:00
D. January 18, 2038 22:14:07
The correct answer is A.The UNIX epoch is January 1, 1970 00:00:00 UTC. On
32-bit systems, the date functions are only guaranteed to work until January 19,
2038.
Question 34
Internally PHP handles dates and times as
A. A ‘date array’ array consisting of the year, month, day, hour, minute, and
second.
B. A UNIX time stamp representing the number of seconds since the UNIX
epoch.
C. An ISO-8601 date entity.
D. A UNIX time stamp consisting of the number of microseconds since the
UNIX epoch.
The correct answer is B. PHP stores all its dates internally as UNIX time stamps,
which are defined as the number of seconds since the UNIX epoch, January 1,
1970 00:00:00 UTC.
Question 35
Your company sells a shopping cart written in PHP. Matching common industry
practice, the shopping cart sends a confirmational email to the user after he has
checked out.
Your team has just ported the shopping cart from PHP on Gentoo Linux to PHP
running on Windows Server 2003.They’ve correctly set the SMTP, smtp_port, and
sendmail_from settings in php.ini, but this error appears when the shopping cart
tries to send the confirmation email:
Could not execute mail delivery program ‘sendmail’
This is your team’s first project using Windows Server, and everyone’s a bit confused
as to why this error is happening.The php.ini settings work fine on Linux,
so what could be the problem?
Choose from one of the following:
A. The smtpserver service hasn’t been started.
B. sendmail_path in php.ini needs to be commented out.
C. Microsoft Exchange needs configuring to accept email from PHP.
D. PHP cannot send email when running on Windows.
The correct answer is B.
Question 36
Flush with the success of the shopping cart on Windows Server 2003, your company
has decided that it would be a good idea to add Solaris to the list of supported
operating systems. Because the shopping cart is already proven to work on
Linux, it should be no trouble at all to get the cart working on Solaris.
Your team goes out and buys a new Sun server. As Solaris doesn’t come with PHP,
you have to compile PHP by hand. At the same time, your network administrator
decides to un-install the Solaris version of sendmail and replace it with the company’s
standard MTA—postfix—instead. He forgets to tell you that he’s done this.
When the time comes to test your shopping cart on Solaris, there’s a problem.
When the shopping cart tries to send the confirmation email, you get this error
message:
Call to undefined function: mail()
What can you do to fix this problem?
A. Put an @ symbol in front of your call to mail() so that PHP does not output
the error message.
B. Put sendmail back on the machine. Postfix doesn’t provide a sendmail wrapper
anyway.
C. Use mb_send_mail() instead.
D. Recompile PHP—after asking your network administrator to leave the
MTA alone until the recompilation of PHP has completed
The correct answer is D.
Question 37
All the new customers you’re attracting on Solaris are very pleased with your
shopping cart.Your product is earning them a lot of new customers also.
However, like all customers, they want new features. Specifically, they want you to
create and attach a simple comma-separated file that users can import into products
such as Microsoft Money.This will make it easier for customers to manage
their finances. Besides, it’s a cool feature that none of your competitors have, so the
marketing department has told your boss to get it done.
At the moment, the shopping cart sends out RFC-822–compliant plain-text
emails.What do you need to change to make it send the attachment as well?
Choose from one of the following:
A. Replace your plain-text emails with MIME-encoded emails.
B. Refuse to do it. RFC-822 doesn’t allow attachments, and your company
should not be shipping products that go against Internet standards.
C. Put the CSV file on a web server, and put a link to it in the email.
D. Ditch PHP’s built-in mail() function, and use the system() command to
call sendmail directly.
The correct answer is A.
Question 38
A rival has just launched a new version of his shopping cart. Unlike yours—which
only sends plain-text emails—his shopping cart sends out confirmation emails that
look more like a web page.These emails look so much nicer, and he’s starting to
eat into your sales as a result. It’s a good thing his cart only runs on Windows; otherwise,
you’d have no customers left!
Something must be done, and marketing has decided that if you can’t beat them,
join them.Your long-suffering boss has been told to make your shopping cart send
out nice-looking emails too. In the best tradition of pointy-haired bosses, he’s
dumped the whole problem in your lap, and is waiting for you to tell him how
this can be done.
What could you do to make this work? Choose one or more of the following:
A. Change your emails to send text/html MIME-encoded emails.
B. It’s time to ditch mail() again and call sendmail directly.
C. Change your emails to send text/enriched MIME-encoded emails.
D. Tell your boss that this only works
on Windows because PHP on Windows
handles emails very differently.
The correct answers are A and C.
Question 39
During testing of your new, much nicer-looking confirmation emails, you notice
that there’s a problem.The email uses quite a few images—including the allimportant
company logo. All of these images are stored on your web server, and
the email uses standard “<img src=…>” tags to include them.The images look
great in your email client—but appear as missing images when you send the email
to your boss to show him the results of your hard work.
Your boss isn’t pleased, and neither is the marketing department, who make it very
clear that you can’t ship the code until the company logo shows up.
The good news is that it isn’t just your email.The confirmation emails sent by
your rival also have this problem. If you can figure out how to make it work, not
only will you be playing catch-up to your rival, but you’ll also be back in the lead.
This mollifies your boss, but gets you nowhere nearer to solving the problem.
What could you change to make this work? Choose one or more of the
following:
A. sendmail is too old. Replace it with a modern MTA instead.
B. Add all the images to the email as attachments with Content-Locations,
and make your email use the attachments rather than the images on the
website.
C. Add a piece of inline JavaScript in your email that temporarily changes the
security settings of the email client.This will enable the images to be downloaded.
D. File a bugwith the author of the email client that your boss uses. Something
must be wrong with the way it handles RFC-1896–compliant email messages.
The correct answer is B—and only B.
Question 40
Which of the following is not an aggregate function?
A. AVG
B. SUM
C. COUNT
D. GROUP BY
E. MIN
The correct answer is D. Group by is a grouping clause, not an aggregate function.
Question 41
In the following query, how will the resultset be sorted?
Select * from my_table order by column_a desc, column_b, column_c
A. By column_a in descending order, by column_b in descending order, and,
finally, by column_c.
B. By column_a, column_b, and column_c, all in descending order.
C. By column_a, column_b, and column_c, all in ascending order.
D. By column_a.Any rows in which column_b has the same value will then be
resorted by column_c in descending order.
E. By column_a in descending order.Any rows in which column_a has the
same value will then be ordered by column_b in ascending order.Any rows
in which both column_a and column_b have the same value will be further
sorted by column_c in ascending order.
E is the correct answer.The resultset of the query will, first of all, be sorted by the
value of column_a in descending order, as dictated by the DESC clause. If, after the
first sorting operation, any rows have the same value for column_a, they will be
further sorted by column_b in ascending order. If any rows have the same value for
column_a and column_b, they will be further sorted by column_c in ascending
order.
Question 42
How is a transaction terminated so that the changes made during its course are
discarded?
A. ROLLBACK TRANSACTION
B. COMMIT TRANSACTION
C. By terminating the connection without completing the transaction
D. UNDO TRANSACTION
E. DISCARD CHANGES
A and C are both valid answers. A transaction is not completed when the connection
between your script and the database server is discarded, as if a ROLLBACK
TRANSACTION command has been issued.
Question 43
The company you work for writes and sells a successful content management system
(CMS). The CMS is written in PHP.
Recently, your company has acquired the assets of one of your main competitors,
including their CMS. The plan is to discontinue the rival CMS, and migrate all of
its current customer base over to your CMS. However, this isn’t going to happen
until you’ve added some of the features that your CMS is currently lacking.
The first feature that you have to add is a dead link checker. This handy little utility
runs from the command-line, and checks a list of URLs to see whether they
still work or not. Thanks to the new streams support in PHP 4.3, this should be
very easy to do.
Unfortunately, the first time you test your code, this error appears on the screen:
Warning: fopen(): URL file-access is disabled in the server configuration in
<file> on line 3
Warning: fopen(URL): failed to open stream: no suitable wrapper could be
found in <file> on line 3
What is the cause of this error? Choose from one of the following.
A. File wrappers don’t allow you to access websites. You need to use the
CURL extension for that.
B. The web server is running behind a firewall, which is preventing access out
to the Internet.C. The web server’s configuration file contains the setting
‘allow_fopen_url=Off ’, which prevents the PHP file wrappers from
working.
D. The php.ini configuration file contains the setting ‘allow_fopen_url=Off ’,
which prevents the PHP file wrappers from working.
The correct answer is D.
Question 44
Now that you’ve fixed that little problem and are able to connect to remote websites
from your PHP script, you’re faced with another problem.
Your script’s job is to determine whether or not a given URL is valid. How is
your script going to do that?
Choose from one or more of the following options.
A. If the fopen() call fails, your script can assume that the remote website no
longer exists.
B. Once you have opened the file wrapper, try reading from the file. If the
read fails, then the remote web page no longer exists.
C. Check the metadata returned by opening the file, and use the HTTP status
code returned by the server to determine whether or not the remote
webpage still exists or not.
D. You can’t use PHP to reliably check whether remote URLs exist or not.
That’s why all these tools are always written in Java.
The correct answers are A and C.
Question 45
Decoding the status code contained in the file wrapper’s metadata is an important
task.
Where should you look to understand what the status code means?
Choose from one or more of the following:
A. The PHP Manual. It’s well annotated, so even if the PHP developers forgot
to list the status codes, you can be sure that a helpful PHP user has added
them somewhere.
B. Microsoft.com. Internet Information Server is the web server of choice for
many companies. Open standards are a nice ideal, but in the real world if
code doesn’t work for customers, you don’t get paid.
C. W3C.org. They set the standards, and standards are important. By supporting
the open standards, you can be sure that your code will work with most
of the products out in the marketplace.
D Apache.org. The Apache web server is more popular than all the other web
servers put together. If your code works with Apache, then it supports the
market leader. And that’s an important position to be in.
The correct answers are B and C.
4.
Question 46
Your boss was so impressed with your new dead link checker tool that he’s given
you responsibility for adding a larger feature to the CMS product proper.
He wants you to add file replication support.
For large websites, it can be very expensive to purchase a server powerful enough
to cope with all the traffic and associated load. It’s often much cheaper to purchase
three or four smaller web servers, with a more powerful server acting as the
admin server. New content is added to the admin server, and then pushed out to
the smaller web servers.
Although most of the content lives in a shared database, original media files (PDF
files, images,Word documents, and the like) are served directly off disk. This is
partly a performance decision, and partly because some database servers have
severe limits on their support for replicating large amounts of binary data.
You must write some code to copy files from the admin server to one or more
web servers. There are no firewalls between the servers.
How would you do this? Choose one or more of the following options.
A. Put the media files into the database, and configure the web servers to
retrieve the files from the database when they are needed.
B. Use file wrappers to write the media files out to a \\server\share network
share.
C. Don’t use file wrappers at all. Use NFS to mount the disks from the admin
server on all the web servers, and access the files directly.
D. Use NFS to mount the disks from the web servers directly onto the admin
server. Have the admin server write to each of the NFS mounts in turn.
The correct answers are B and D.
Question 47
Customers are fickle things.
Just as you have your new file replication code working, one of your major customers
informs you that they have installed a firewall between the admin server
and the web servers.
This totally prevents your file replication code from working.
Helpfully, the customer does allow outgoing HTTP connections through the firewall.
You’ll need to provide an alternative script, that uploads the files to the web
servers through a HTTP connection. How are you going to do that?
Choose from one or more of the following.
A. File wrappers can’t upload files via http. You’ll have to use the CURL
extension to achieve this.
B. Just open a URL as a file and write to it. The whole point of file wrappers
is to make operations like this easy.
C. Use the stream context to tell the http file wrapper where to upload the file,
and have a script on the web servers move the file from the uploads directory
to their final destination.
D. Use the FTP file wrapper to upload files directly to their final destination.
The correct answer is C.
Question 48
With file replication done and dusted, your boss is confident that he’ll soon have
customers migrating across from the discontinued CMS to your product. He’ll
have no trouble making his targets for the quarter, and earning his bonus.
However, he needs one more feature porting across before he can be certain that
customers will start migrating.
Many sites like to keep in touch with their customers via a weekly newsletter.
Many customers only come back to the website because there was something of
interest to them in the newsletter. Being able to send newsletters—and being able
to make those newsletters look professional—is an important feature.
Your CMS doesn’t support the concept of newsletters per se. But it does support
the idea of packaging groups of files for downloading. If you could write a userdefined
file wrapper that makes a MIME email look just like a ZIP file, it would
then be very easy to add newsletter support.
Sketch out a design for a file wrapper, which would allow a PHP script to add
content, graphics, and other attachments to a MIME email.
Question 49
Which of the following data filtering methods can be described as a whitelist
approach?
A. Make sure that a username does not contain backticks or angled brackets.
B. Only allow alphanumerics and underscores in a username.
C. Pass all incoming data through strip_tags().
D. Use htmlentities() to escape potentially malicious characters.
Answer B is correct. Answer A is incorrect because this assumes that any username
without backticks or angled brackets is valid. Answer C is incorrect because this
only removes HTML and PHP tags, assuming everything else to be valid. Answer
D is incorrect because htmlentities() only encodes HTML entities and is not
intended to filter data at all.
Question 50
With register_globals enabled, which of the following practices is particularly
important?
A. Initialize all variables.
B. Filter all foreign data.
C. Escape all data used in SQL statements.
D. Escape all data prior to output.
Answer A is correct. Answers B, C, and D are incorrect because these practices are
not dependent on whether register_globals is enabled
Question 51
What are the two most important practices to mitigate the risk of an SQL injection
vulnerability?
A. Disabling register_globals and enabling safe_mode.
B. Enabling safe_mode and filtering any data used in the construction of the
SQL statement.
C. Filtering and escaping any data used in the construction of the SQL statement.
D. Disabling register_globals and escaping any data used in the construction
of the SQL statement.
Answer C is correct.With properly filtered data, escaping any metacharacters that
remain can mitigate the remaining risks. Answers A, B, and D are incorrect because
register_globals does not directly affect the risk of SQL injection, and
safe_mode is unrelated
Question 52
If $foo is anticipated to be a string, what modification made to the following
query will mitigate the risk of an SQL injection vulnerability?
$sql = “insert into mytable values ($foo)”;
A. Specify the column name in the SQL statement.
B. Remove the parentheses surrounding $foo.
C. Replace the parentheses surrounding $foo with single quotes.
D. Add single quotes around $foo
Answer D is correct. Answer A is incorrect because specifying the column name
does not affect the behavior of the SQL statement. Answers B and C are incorrect
because the parentheses are required.
Question 53
What is the purpose of the escapeshellcmd() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D. To prevent cross-site scripting attacks
Answer C is correct. Answer A is incorrect because escapeshellcmd() does not
attempt to solve this problem. Answer B is incorrect because escapeshellcmd()
does not actually remove characters. Answer D is incorrect because escaping data
to protect against cross-site scripting is much different than escaping data to be
used in a shell command.
Question 54
What is the purpose of the escapeshellarg() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D To remove arguments from a shell command
Answer A is correct. Answers B and D are incorrect because escapeshellarg()
does not remove characters. Answer C is incorrect because escapeshellarg()
does not attempt to solve this problem.
Question 55
When is cross-site scripting a heightened risk?
A. When storing data submitted by the user.
B. When displaying foreign data.
C. When executing a shell command.
D. When opening a remote URL.
Answer B is correct.When displaying foreign data that is not properly escaped, you
can inadvertently expose your users to significant risk. Answer A is incorrect
because storing data poses no immediate threat, even though this might result in a
cross-site scripting vulnerability later. Answers C and D are incorrect because these
activities are unrelated.
Question 56
Which of the following functions can be used to escape data such that it can be
displayed without altering the appearance of the original data?
A. htmlspecialchars()
B. addslashes()
C. escapeshellargs()
D. urlencode()
Answer A is correct because htmlspecialchars() will convert special characters
to HTML entities that will display correctly in any Web client. Answer B is incorrect
because addslashes() only escapes single quotes. Answer C is incorrect
because escapeshellargs() is only helpful when dealing with shell command
arguments. Answer D is incorrect because URL encoding is not interpreted by
Web clients except in the context of URLs.
Question 57
What is the purpose of the open_basedir directive?
A. To indicate the directory that include() calls will use as a base.
B. To restrict file open access to a specific directory.
C. To set the working directory.
D. To allow additional file open access than that granted by safe_mode.
A. To indicate the directory that include() calls will use as a base.
B. To restrict file open access to a specific directory.
C. To set the working directory.
D. To allow additional file open access than that granted by safe_mode.
Answer B is correct. Answer A is incorrect because the behavior of include() is
unchanged. Answer C is incorrect because the working directory does not depend
on open_basedir. Answer D is incorrect because open_basedir is not affected by
whether safe_mode is enabled.
Question 58
Which of the following activities can safe_mode help prevent?
A. Browsing the filesystem with a specially crafted PHP script.
B. Writing a Bash shell script to read session data.
C. Browsing the filesystem with a specially crafted Perl script.
D. Accessing another user’s database.
Answer A is correct because you’ll only be able to browse files that have the same
ownership as your PHP script. Answers B and C are incorrect because safe_mode
cannot affect scripts written in other languages. Answer D is incorrect because
safe_mode does not attempt to prevent database access.
Question 59
How can the following line of code be improved?
$db->query(“insert into foo values($id,$bar)”);
A. Use addslashes and sprintf to avoid security holes and make the code
cleaner
B. Split the query over several lines
C. Use mysql_query() instead of $db->query()
D. Define the table fields that will be affected by the INSERT statement
E. Use mysql_query()instead of $db->query() and addslashes to avoid
security holes
Answers A, B, and D are correct. First of all, you need to ensure that the query is
secure; this is done by executing addslashes (or the equivalent function for your
DBMS of choice) to prevent scripting attacks. If your query is long, it’s not a bad
idea to split it over several lines to get a better overview of your code. Use
sprintf() where possible to make the code cleaner. Finally it’s always a good idea
to define the table fields that will be filled by an INSERT statement to prevent
unexpected errors if the table changes.
Question 60
You developed a big application accessed by several thousand users at the same
time. Suddenly, your web server stops responding and users are getting connection
errors.What could have happened?
A. The database server was terminated because of the unusually high amount of
database accesses.
B. The web server was misconfigured so that it ran into virtual memory usage
and consequent resource starvation because of too many child processes.
C. You didn’t optimize your code design properly.
Answer B is correct. Although it could be possible that the database server was
killed because of the many requests from the users, they should at least be able to
see the HTML pages from the website because the web server would still be running.
If connections are timing out, it is likely that the server ran into swap space
because of misconfiguration of the number of concurrent web server child
processes and crashed because of resource starvation.
Question 61
You are in a team of developers working on a number of different business applications.
Your project manager tells you that in two weeks another three PHP
developers will join the team and that you have to ensure that they will be ready
to dive in to the current PHP code without problems.What could you do?
A. Write proper end user documentation on how to use the web front end.
B. Write proper end user documentation and generate proper PHPDoc comments
inside the code to get an API documentation.
C. The absence of documentation will actually encourage the new developers
to delve more deeply into the code.
Answer B is correct—or, at least, as correct as you can get in a general situation.
The key here is that you should write proper documentation at the same time as
you’re writing your code.You could then use a tool such as PHPDocumentor to
generate a nicely formatted API documentation in HTML or PDF and make it
available to any new developers who join your team.
Question 62
Suppose that you are receiving input from the user in the form of the string
“0mydeviceid” for a field for which you only allow valid numeric values.You
want to test if this variable is equal to 0 and, if it isn’t, output an error.Which
comparison operation should you use?
A. (0 = “0mydeviceid”)
B. (0 == “0mydeviceid”)
C. (0 === “0mydeviceid”)
D. None of the above
Answer D is correct. Because PHP is automatically trying to convert the string
“0mydeviceid” to 0 when comparing it with the equal operator == , your condition
in answer B evaluates to true even though the user input is not a valid numeric
value.The expression in answer C, on the other hand, correctly determines that
the user input is not a valid integer—but that will always be the case because
you’re likely to always receive user input in the form of a string—so, even if that
string can be converted to an integer value, the identity test will fail.
Question 63
Which of the following strings are not valid modes for the fopen() function?
A. a+b
B. b+a
C. at
D. w
E. x+
B
Question 64
Consider the following piece of code:
<?php
$arr = array(3 => “First”, 2=>“Second“, 1=>“Third“);
list (, $result) = $arr;
?>
After running it, the value of $result would be
A. First
B. Second
C. Third
D. This piece of code will not run, but fail with a parse error.
C
Question 65
In standard SQL-92, which of these situations do not require or cannot be handled
through the use of an aggregate SQL function? (Choose 2)
A. Calculating the sum of all the values in a column.
B. Determining the minimum value in a result set.
C. Grouping the results of a query by one or more fields.
D. Calculating the sum of all values in a column and retrieving all the values of
another column that is not part of an aggregate function or GROUP BY clause.
E. Determining the mean average of a column in a group of rows.
C AND D
Question 66
array_multisort or array_multisort()
Question 67
When using the default session handler files for using sessions, PHP stores
session information on the harddrive of the webserver.When are those session
files cleaned up?
A. PHP will delete the associated session file when session_destroy() is
called from within a script.
B. When the function session_cleanup() is called, PHP will iterate over all
session files, and delete them if they exceeded the session timeout limit.
C. When the function session_start() is called, PHP will iterate over all
session files, and delete them if they exceeded the session timeout limit.
D. When the function session_start() is called, PHP will sometimes iterate
over all session files, and delete them if they exceeded the session timeout
limit.
E. Session files are never removed from the filesystem, you need to use an automated
script (such as a cronjob) to do this.
D
Question 68
What is the order of parameters in the mail() function?
A. subject, to address, extra headers, body
B. to address, subject, extra headers, body
C. to address, subject, body, extra headers
D. subject, to address, body, extra headers
C
Question 69
Which of the following statements are correct? (Choose 3)
A. sprintf() does not output the generated string.
B. printf(“%2s%1s“, “ab“, “c“) outputs the string abc.
C. vprintf() takes at least one parameter; the first parameter is the formatting
string and the following parameters are the arguments for the ‘%’
placeholders.
D. printf(“%c“, “64“) will output @ and not 6.
E. sprintf(“%3.4f“, $x) outputs more than 7 characters.
F. number_format() inserts thousands of separators and decimal points different
from (,) and (.) respectively, while printf() like functions always use
(.) as decimal point.
A, D, and F
Question 70
The requirement is to return true for the case in which a string $str contains
another string $substr after the first character of $str? Which of the following
will return true when string $str contains string $substr, but only after the first
character of $str?
I.
<?php
function test($str, $substr) {
return strpos(substr($str,1), $substr) >= 0;
\}
?>
II.
<?php
function test($str, $substr) {
return strrchr($str, $substr) !== false;
\}
?>
III.
<?php
function test($str, $substr) {
return strpos($str, $substr) > 0;
\}
?>
A. I only
B. II only
C. III only
D. I and II
E. I and III
F. II and III
C
Question 71
Which of the features listed below do not exist in PHP4? (Choose 2)
A. Exceptions
B. Preprocessor instructions
C. Control structures
D. Classes and objects
E. Constants
A AND B
Question 72
What is the output of the following code snippet?
<?php
class Vehicle {
\}
class Car extends Vehicle {
\}
class Ferrari extends Car {
\}
var_dump(get_parent_class(“Ferrari”));
?>
A. string(7) “Vehicle“
B. string(3) “Car“
C. array(2) {
[0]=>
string(7) “vehicle“
[1]=>
string(3) “car“
\}
A
Question 73
The following PHP script is designed to subtract two indexed arrays of numbers.
Which statement is correct?
<?php
$a = array(5, 2, 2, 3);
$b = array(5, 8, 1, 5);
var_dump(subArrays($a, $b));
function
subArrays($arr1,
$arr2)
{
$c = count($arr1);
if
($c != count($arr2))
return
null;
for($i = 0;
$i < $c;
$i++)
$res[$i]
$arr1[$i] – $arr2[$i];
return $res;
\}
?>
A. The script is valid.
B. Assignments must be made on a single line.
C. It has too many linefeed characters between statements.
D. No, the script is missing curly braces.
E. Yes it is valid, but the script will not work as expected.
B
Question 74
What is the purpose of the escapeshellarg() function?
A. Removing malicious characters.
B. Escaping malicious characters.
C. Creating an array of arguments for a shell command.
D. Preparing data to be used as a single argument in a shell command.
E. None of the above.
D
Question 75
The _________ function can be used to determine if the contents of a string can
be interpreted as a number.
is_numeric or is_numeric()
Question 76
Assume $comment contains a string.Which PHP statement prints out the first 20
characters of $comment followed by three dots (.)?
A. print substr($comment, 20) . ‘…‘;
B. print substr_replace($comment, ‘…‘, 20);
C. print substr($comment, 20, strlen($comment)) . ‘…‘;
D. print substr_replace($comment, 20, ‘…‘);
B
Question 77
What is the name of the function that you should use to put uploaded files into a
permanent location on your server?
move_uploaded_file or move_uploaded_file
Question 78
If you have a file handle for an opened file, use the __________ function to send
all data remaining to be read from that file handle to the output buffer.
fpassthru or fpassthru()
Question 79
Which of the following sentences are not true? (Choose 2)
A. strpos() allows searching for a substring in another string.
B. strrpos() allows searching for a substring in another string.
C. strpos() and strrchr() return -1 if the second parameter is not a substring
of the first parameter.
D. strpos() and strrpos() can return a value that is different from an integer.
E. The second parameter to substr() is the length of the substring to extract.
F. strstr() returns false if the substring specified by its second parameter is
not found in the first parameter.
C AND E
Question 80
Which of the following sentences are correct? (Choose 2)
A. time() + 60*60*100 returns the current date and time plus one hour.
B. time() + 24*60*60 returns the current date and time plus one day.
C. time() + 24*60*60*100 returns the current date and time plus one day
B
* Mysql interview questions
Mysql interview questions and answers are below
| Questions : 1 | how to do login in mysql with unix shell |
| Answers :1 | By below method if password is pass and user name is root # [mysql dir]/bin/mysql -h hostname -u root -p pass |
| Questions : 2 | how you will Create a database on the mysql server with unix shell |
| Answers : 2 | mysql> create database databasename; |
| Questions : 3 | how to list or view all databases from the mysql server. |
| Answers : 3 | mysql> show databases; |
| Questions : 4 | How Switch (select or use) to a database. |
| Answers : 4 | mysql> use databasename; |
| Questions : 5 | How To see all the tables from a database of mysql server. |
| Answers : 5 | mysql> show tables; |
| Questions : 6 | How to see table’s field formats or description of table . |
| Answers : 6 | mysql> describe tablename; |
| Questions : 7 | How to delete a database from mysql server. |
| Answers : 7 | mysql> drop database databasename; |
| Questions : 8 | How we get Sum of column |
| Answers : 8 | mysql> SELECT SUM(*) FROM [table name]; |
| Questions : 9 | How to delete a table |
| Answers : 9 | mysql> drop table tablename; |
| Questions : 10 | How you will Show all data from a table. |
| Answers : 10 | mysql> SELECT * FROM tablename; |
| Questions : 11 | How to returns the columns and column information pertaining to the designated table |
| Answers : 11 | mysql> show columns from tablename; |
| Questions : 12 | How to Show certain selected rows with the value "pcds" |
| Answers : 12 | mysql> SELECT * FROM tablename WHERE fieldname = "pcds"; |
| Questions : 13 | How will Show all records containing the name "sonia" AND the phone number ’9876543210′ |
| Answers : 13 | mysql> SELECT * FROM tablename WHERE name = "sonia" AND phone_number = ’9876543210′; |
| Questions : 14 | How you will Show all records not containing the name "sonia" AND the phone number ’9876543210′ order by the phone_number field. |
| Answer : 14 | mysql> SELECT * FROM tablename WHERE name != "sonia" AND phone_number = ’9876543210′ order by phone_number; |
| Questions : 15 | How to Show all records starting with the letters ‘sonia’ AND the phone number ’9876543210′ |
| Answers : 15 | mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = ’9876543210′; |
| Questions : 16 | How to show all records starting with the letters ‘sonia’ AND the phone number ’9876543210′ limit to records 1 through 5. |
| Answers : 16 | mysql> SELECT * FROM tablename WHERE name like "sonia%" AND phone_number = ’9876543210′ limit 1,5; |
| Questions : 16 | Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with r. |
| Answer : 16 | mysql> SELECT * FROM tablename WHERE rec RLIKE "^r"; |
| Questions : 17 | How you will Show unique records. |
| Answer : 17 | mysql> SELECT DISTINCT columnname FROM tablename; |
| Questions : 18 | how we will Show selected records sorted in an ascending (asc) or descending (desc) |
| Answer : 18 | mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;
mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC; |
| Questions : 19 | how to Return total number of rows. |
| Answers : 19 | mysql> SELECT COUNT(*) FROM tablename; |
| Questions : 20 | How to Join tables on common columns. |
| Answer : 20 | mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id |
| Questions : 21 | How to Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs. |
| Answer : 21 | # mysql -u root -p
mysql> use mysql; mysql> INSERT INTO user (Host,User,Password) VALUES(‘%’,'username’,PASSWORD(‘password’)); mysql> flush privileges; |
| Questions : 22 | How to Change a users password from unix shell. |
| Answers : 22 | # [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password ‘new-password’ |
| Questions : 23 | How to Change a users password from MySQL prompt. Login as root. Set the password. Update privs. |
| Answer : 23 | # mysql -u root -p
mysql> SET PASSWORD FOR ‘user’@'hostname’ = PASSWORD(‘passwordhere’); mysql> flush privileges; |
| Questions : 24 | How to Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server. |
| Answer : 24 | # /etc/init.d/mysql stop # mysqld_safe –skip-grant-tables & # mysql -u root mysql> use mysql; mysql> update user set password=PASSWORD("newrootpassword") where User=’root’; mysql> flush privileges; mysql> quit # /etc/init.d/mysql stop # /etc/init.d/mysql start |
| Questions : 25 | How to Set a root password if there is on root password. |
| Answer : 25 | # mysqladmin -u root password newpassword |
| Questions : 26 | How to Update a root password. |
| Answer : 26 | # mysqladmin -u root -p oldpassword newpassword |
| Questions : 27 | How to allow the user "sonia" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs. |
| Answers : 27 | # mysql -u root -p mysql> use mysql; mysql> grant usage on *.* to sonia@localhost identified by ‘passwd’; mysql> flush privileges; |
| Questions : 28 | How to give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs. |
| Answers : 28 | # mysql -u root -p mysql> use mysql; mysql> INSERT INTO user (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES (‘%’,'databasename’,'username’,'Y’,'Y’,'Y’,'Y’,'Y’,'N’); mysql> flush privileges; or mysql> grant all privileges on databasename.* to username@localhost; mysql> flush privileges; |
| Questions : 29 | How To update info already in a table and Delete a row(s) from a table. |
| Answer : 29 | mysql> UPDATE [table name] SET Select_priv = ‘Y’,Insert_priv = ‘Y’,Update_priv = ‘Y’ where [field name] = ‘user’; mysql> DELETE from [table name] where [field name] = ‘whatever’; |
| Questions : 30 | How to Update database permissions/privilages. |
| Answer : 30 | mysql> flush privileges; |
| Questions : 31 | How to Delete a column and Add a new column to database |
| Answer : 31 | mysql> alter table [table name] drop column [column name]; mysql> alter table [table name] add column [new column name] varchar (20); |
| Questions : 32 | Change column name and Make a unique column so we get no dupes. |
| Answer : 32 | mysql> alter table [table name] change [old column name] [new column name] varchar (50); mysql> alter table [table name] add unique ([column name]); |
| Questions : 33 | How to make a column bigger and Delete unique from table. |
| Answer : 33 | mysql> alter table [table name] modify [column name] VARCHAR(3); mysql> alter table [table name] drop index [colmn name]; |
| Questions : 34 | How to Load a CSV file into a table |
| Answer : 34 | mysql> LOAD DATA INFILE ‘/tmp/filename.csv’ replace INTO TABLE [table name] FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’ (field1,field2,field3); |
| Questions : 35 | How to dump all databases for backup. Backup file is sql commands to recreate all db’s. |
| Answer : 35 | # [mysql dir]/bin/mysqldump -u root -ppassword –opt >/tmp/alldatabases.sql |
| Questions : 36 | How to dump one database for backup. |
| Answer : 36 | # [mysql dir]/bin/mysqldump -u username -ppassword –databases databasename >/tmp/databasename.sql |
| Questions : 37 | How to dump a table from a database. |
| Answer : 37 | # [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql |
| Questions : 38 | Restore database (or database table) from backup. |
| Answer : 38 | # [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql |
| Questions : 39 | How to Create Table show Example |
| Answer : 39 | mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255)); |
| Questions : 40 | How to search second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load? |
| Answers : 40 |
By below query we will get second maximum(second highest) salary value(integer)from table employee (field salary)in the manner so that mysql gets less load? |
* MySQL Indexing
MySQL Index – Speed and Extra Overhead
Indexes are created on a per column basis. If you have a table with the columns: name, age, birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries, then you would need to create an index for employeeID. When you create this index, MySQL will build a lookup index where employeeID specific queries can be run quickly. However, the name, age and birthday queries would not be any faster.
Indexes are something extra that you can enable on your MySQL tables to increase performance,cbut they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.
Creating a MySQL Index – New Table
If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. We have created two fields: name and employeeID (index).
MySQL Code:
CREATE TABLE employee_records ( name VARCHAR(50), employeeID INT, INDEX (employeeID) )
Creating a MySQL Index – Existing Table
You can also add an index to an older table that you think would benefit from some indexing. The syntax is very similar to creating an index in a new table. First, let’s create the table.
MySQL Code:
CREATE TABLE employee_records2 (name VARCHAR(50), employeeID INT)
With our newly created table we are going to update the “employee_records2″ table to include an index.
MySQL Code:
CREATE INDEX id_index ON employee_records2(employeeID)
We keep our existing employeeID field and create a new index id_index that is made up of employeeID data.
* .htaccess interview questions
The many benefits of .htaccess files
Apache HTTP Server is controlled by a series of directives, which are usually placed inside Apache’s main configuration file. The file is often called httpd.conf or apache2.conf. This configuration file is located in the /etc directory in Linux, and any changes you make to the file, which you must edit as root, will affect all of the server’s websites.
If you only want to change one website, making changes to your Apache configuration file is probably a bad idea. Fortunately, Apache allows users to place hidden files, called .htaccess, in their Web document directories that can also run Apache directives. When .htaccess is enabled on a server, it can be a very powerful tool.
To enable support for .htaccess on your dedicated server, locate the line in your configuration file that reads:
AllowOverride None
and change it to:
AllowOverride All
Here are a few .htaccess examples:
Access Control. Simply put, you can deny visitors from accessing certain parts of your site. You might have a directory that contains scripts. Your server runs the scripts, but you do not want outsiders to have access to them. Put the following line in an .htaccess file in that directory:
deny from all
Custom Error Documents. This is very useful if you want users to not feel lost when they reach the dreaded 404 Not Found, which is a plain white page with information about Apache and your OS. To create custom error documents, edit your root document .htaccess file and enter something like:
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
Then, create the files in the directory you have specified, making custom error documents. You can be as creative as you want.
Mod rewrite. With the Apache rewrite module, you can change the way URLs appear to web browsers and search engines.
For example, to change a URL like http://mydomain.com/index.php?page=creative to something more friendly, put the following lines in an .htaccess file:
RewriteEngine on
RewriteRule ^([^/.]+).html$ index.php?page=$1 [L]
Your URL will now appear as: http://mydomain.com/creative.html.
There are numerous other uses for .htaccess, and Apache documentation contains a list of all available directives. Best of all, if you ever need to undo something, simply remove whatever directive you have set in place without having to restart Apache. Enjoy!
* JSON interview questions
JSON interview questions and answer are below
| Questions : 1 | What is The JSON(JavaScript Object Notation) ? |
| Answers : 1 |
JavaScript Object Notation(JSON) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. And JSON is language-independent, with parsers available for virtually every programming language. Uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python,php The JSON format is often used for serializing and transmitting structured data over a network connection. When third party data interchane(REST Services) then JSON may used there LIKE SHOP .It is primarily used to transmit data between a server and web application, serving as an alternative to XML. |
| Questions : 2 | Who is the Father or creater of JSON ? |
| Answers : 2 | Douglas Crockford called as the Father of JSON |
| Questions : 3 | what the file extension of JSON |
| Answers : 3 | The JSON filename extension is .json. |
| Questions : 4 | Explain Json with php |
| Answer : 4 | Json is too much easy with php There is no installation needed to use these functions; they are part of the PHP core. nothing more need to know just only use { ,[ and create json format string and use three php function json_encode() to get JSON representation of a value, json_decode() for Decodes a JSON string, ¦json_last_error() to get the last error occurred in process. write your desire string in below format and use php funtions :
$string='{ "firstName": "Rohit", "lastName": "Singh", "age": 26, "address": { "streetAddress": "Mira Road Thane ", "city": "Mumbai", "state": "maharshtra", "postalCode": "401107" }, "phoneNumber": [ { "type": "home", "number": "022 333-1234" }, { "type": "fax", "number": "022 444-4567" } ] }’; $decodeString = json_decode($string); echo ‘First Name – ‘.$decode->{“firstName”}; echo ‘Last Name – ‘.$decode->{“lastName”}; echo ‘Address – ‘.$decode->{“address”}->{“streetAddress”}; Out put : Print below First Name – Rohit Last Name – Singh Address – Mira Road Thane |
| Questions : 5 | Why Use JSON over XML |
| Answers : 5 | • Lighter and faster than XML as on-the-wire data format• JSON objects are typed while XML data is typeless
> JSON types: string, number, array, boolean, > XML data are all string • Native data form for JavaScript code > Data is readily accessible as JSON objects in your JavaScript code vs. XML data needed to be parsed and assigned to variables through tedious DOM APIs > Retrieving values is as easy as reading from an object property in your JavaScript code |
| Questions : 6 | Explain JSON Structures |
| Answers : 6 | • A collection of name/value pairs> In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array
• An ordered list of values > In most languages, this is realized as an array, vector, list, or sequence • These are universal data structures supported • A JSON object is an unordered set of name/value pairs • A JSON object begins with { (left brace) and ends with } (right brace) • Each name is followed by : (colon) and the name/value pairs are separated by , (comma) |
| Questions : 7 | Compare JSON with JavaScript |
| Answers : 7 | • JSON is a subset of the object literal notation of JavaScript> JSON can be used in the JavaScript language with no muss or fuss
Example: JSON Object var myJSONObject = {“bindings”: [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}, {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} ] }; • In this example, a JSON JavaScript object is created containing a single member “bindings”, which contains an array containing three objects, each containing “ircEvent”, “method”, and “regex” members • Members can be retrieved using dot or subscript operators myJSONObject.bindings[0].method // “newURI” Text to Object Conversion in JavaScript code var myObject = eval(‘(‘ + myJSONtext + ‘)’); • To convert a JSON text into an JSON object, use the eval() function > eval() invokes the JavaScript compiler > Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure |
| Questions : 8 | what the Security and JSON Parser |
| Answers : 8 | Security and JSON Parser to understand by below examples// Include http://www.json.org/json.js
var myObject = myJSONtext.parseJSON(); • eval() can compile and execute any JavaScript program, so there can be security issues (cross-site scripting) > Use eval() when the source can be trusted • When security is a concern – the source cannot be trusted -, it is better to use a JSON parser > A JSON parser will only recognize JSON text and so is much safer Object to Text Conversion var myJSONText = myObject.toJSONString(); • You can convert JSON object into JSON text • JSON does not support cyclic data structure > Do not give cyclical structures to the JSON stringifier |
| Questions : 9 | Do you know JSON Tools for Java Developer |
| Answers : 9 | Ya some of JSON tool for java developer is• Parser
> Parse JSON text files and convert these to a Java model • Renderer > Render a Java representation into text • Serializer > Serialize plain POJO clusters to a JSON representation • Validator > Validate the contents of a JSON file using a JSON schema JSONObject Java Class • A JSONObject is an unordered collection of name/value pairs • The put methods adds a name/value pair to an object • The texts produced by the toString methods strictly conform to the JSON syntax rules myString = new JSONObject().put(“JSON”, “Hello, World!”).toString(); // myString is {“JSON”: “Hello, World”} |
| Questions : 10 | How to Generate or Send JSON Data at the Server Side |
| Answers : 10 | • Create JSONObject Java object• Add name and value pairs using put method
• Convert it to String type using toString method and send it to the client with content-type as “text/xml” or “text/plain” myString = new JSONObject().put(“JSON”, “Hello, World!”).toString(); // myString is {“JSON”: “Hello, World”} |
| Questions : 11 | How to Receive JSON Data at the Client Side |
| Answers : 11 | • JSON data is received as a string• Calling eval() will generate JSON object in JavaScript code
> var JSONdata = eval(req.responseText); • Once you have JSON object, you can use . notation to access its properties > var name = JSONdata.name; > var address = JSONdata.addresses[3]; > var streetname = JSONdata.addresses[3].street; |
| Questions : 12 | How to Generate/Send JSON Data at the Client Side |
| Answers : 12 | • Create JSON JavaScript object• Use “POST” HTTP method in the open method of the XMLHttpRequest object
• Pass JSON JavaScript object in the send method of XMLHttpRequest object var carAsJSON = JSON.stringify(car); var url = “JSONExample?timeStamp=” + new Date().getTime(); createXMLHttpRequest(); xmlHttp.open(“POST”, url, true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”); xmlHttp.send(carAsJSON); |
| Questions : 13 | How to Receive JSON Data at the Server Side |
| Answers : 13 | • Read the JSON data as a String type• Create JSONObject Java object from the string String json = readJSONStringFromRequestBody(request);
//Use the JSON-Java binding library to create a JSON object in Java JSONObject jsonObject = null; try { jsonObject = new JSONObject(json); } catch(ParseException pe) { } |
| Questions : 14 | What is JSON-RPC? What is JSON-RPC-Java? |
| Answers : 14 | • JSON-RPC is a simple remote procedure call protocol similar to XML-RPC although it uses the lightweight JSON format instead of XML• JSON-RPC-Java is a Java implementation of the JSON-RPC protocol |
| Questions : 15 | Why JSON-RPC-Java? |
| Answers : 15 | • It allows you to transparently call server-side Java code from JavaScript with an included lightweight JSON-RPC JavaScript client• It is designed to run in a Servlet container such as Tomcat and can be used with J2EE Application servers to allow calling of plain Java or EJB methods from within a JavaScript DHTML web application |
| Questions : 16 | Features of JSON-RPC-Java |
| Answers : 16 | • Dynamically call server-side Java methods from JavaScript DHTML web applications. No Page reloading.• Asynchronous communications.
• Transparently maps Java objects to JavaScript objects. • Lightweight protocol similar to XML-RPC although much faster. • Leverages J2EE security model with session specific exporting of objects. • Supports Internet Explorer, Mozilla, Firefox, Safari, Opera and Konqueror |
* jQuery interview questions
jQuery interview questions and answers are below
| Questions : 1 | What is jQuery ? |
| Answers : 1 | It’s very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you |
| Questions : 2 | How you will use Jquery means requirement needed for using jquery |
| Answers : 2 | Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript filelike below :< script src=”jquery.js” language=”javascript” type=”text/javascript”> |
| Questions : 3 | what the use of $ symbol in Jquery |
| Answers : 3 | $ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery |
| Questions : 4 | How do you select an item using css class or ID and get the value by use of jquery |
| Answers : 4 | If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code$(‘#MyId’) for ID and for classs $(‘.MyClass’) and for valuevar myValue = $(‘#MyId’).val(); // get the value in var Myvalue by id
Or for set the value in selected item $(‘#MyId’).val(“print me”); // set the value of a form input |
| Questions : 5 | How to get the server response from an AJAX request using Jquery? |
| Answers : 5 | When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.Below an example of making an AJAX call and alerting the response (or error):
$.ajax({ url: ‘pcdsEmpRecords.php’, success: function(response) { alert(response); }, error: function(xhr) { alert(‘Error! Status = ‘ + xhr.status); } }); |
| Questions : 6 | How do you update ajax response with id ” resilts” |
| Answers : 6 | By using below code we can update div content where id ‘results’ with ajax responsefunction updateStatus() {
$.ajax({ url: ‘pcdsEmpRecords.php’, success: function(response) { // update div id Results $(‘#results’).html(response); } }); } |
| Questions : 7 | How do You disable or enable a form element? |
| Answers : 7 | There are two ways to disable or enable form elements.Set the ‘disabled’ attribute to true or false:
// Disable #pcds $(‘#pcds’).attr(‘disabled’, true); // Enable #pcds $(‘#pcds’).attr(‘disabled’, false); Add or remove the ‘disabled’ attribute: // Disable #pcds $(“#pcds”).attr(‘disabled’, ‘disabled’); // Enable #x $(“#pcds”).removeAttr(‘disabled’); |
| Questions : 8 | How do you check or uncheck a checkbox input or radio button? |
| Answers : 8 | There are two ways to check or uncheck a checkbox or radio button.Set the ‘checked’ attribute to true or false.
// Check #pcds $(‘#pcds’).attr(‘checked’, true); // Uncheck #pcds $(‘#pcds’).attr(‘checked’, false); Add or remove the ‘checked’ attribute: // Check #pcds $(“#pcds”).attr(‘checked’, ‘checked’); // Uncheck #pcds $(“#pcds”).removeAttr(‘checked’); |
| Questions : 9 | How do you get the text value of a selected option? |
| Answers : 9 | Select elements typically have two values that you want to access.First there’s the value to be sent to the server, which is easy: $(“#pcdsselect”).val(); // => 1
The second is the text value of the select. For example, using the following select box: <select id=”pcdsselect”> <option value=”1″>Mr</option> <option value=”2″>Mrs</option> <option value=”3″>Ms</option> <option value=”4″>Dr</option> <option value=”5″>Prof</option> </select> If you wanted to get the string “Mr” if the first option was selected (instead of just “1″), you would do that in the following way: $(“#mpcdsselect option:selected”).text(); // => “Mr” |
* HTML5 interview questions
Top HTML5 interview questions and answers
| Questions : 1 | What is the difference between HTML and HTML5 ? | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 1 | HTML5 is nothing more then upgreaded version of HTML where in HTML5 Lot of new future like Video, Audio/mp3, date select function , placeholder , Canvas, 2D/3D Graphics, Local SQL Database added so that no need to do external plugin like Flash player or other library | |||||||||||||||||||||||||||||||||||||||||||||
| Questions : 2 | What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ? | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 2 | The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. AND The <!DOCTYPE> tag does not have an end tag and It is not case sensitive.
The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag. As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD). |
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 3 | How many New Markup Elements you know in HTML5 | |||||||||||||||||||||||||||||||||||||||||||||
| Answer : 3 | Below are the New Markup Elements added in HTML5
|
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 4 | What are the New Media Elements in HTML5? is canvas element used in HTML5 | |||||||||||||||||||||||||||||||||||||||||||||
| Answer : 4 | Below are the New Media Elements have added in HTML5
yes we can use Canvas element in html5 like below <canvas> |
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 5 | Do you know New Input Type Attribute in HTML5 | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 5 | Yes we can use below new input type Attribute in HTML5
|
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 6 | How to add video and audio in HTML5 | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 6 | Like below we can add video in html5
<video width=”320″ height=”240″ controls=”controls”> <source src=”pcds.mp4″ type=”video/mp4″ /> <source src=”pcds.ogg” type=”video/ogg” /> </video> And audie like this <audio controls=”controls”> <source src=”song.ogg” type=”audio/ogg” /> <source src=”song.mp3″ type=”audio/mpeg” /> </audio> |
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 7 | What the use of Canvas Element in HTML5 | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 7 | The canvas element is used to draw graphics images on a web page by using javascript like below
<canvas id=”pcdsCanvas” width=”500″ height=”400″></canvas> <script type=”text/javascript”> var pcdsCanvas=document.getElementById(“pcdsCanvas”); var pcdsText=pcdsCanvas.getContext(“2d”); pcdsText.fillStyle=”#82345c”; pcdsText.fillRect(0,0,150,75); </script> |
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 8 | What is the use of localStorage in HTML5 ? | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 8 | Before HTML5 LocalStores was done with cookies. Cookies are not very good for large amounts of data, because they are passed on by every request to the server, so it was very slow and in-effective.
In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website’s performance.and The data is stored in different areas for different websites, and a website can only access data stored by itself. And for creating localstores just need to call localStorage object like below we are storing name and address <script type=”text/javascript”> localStorage.name=”PCDS”; document.write(localStorage.name); </script> <script type=”text/javascript”> localStorage.address=”Mumbai India..”; document.write(localStorage.address); </script> |
|||||||||||||||||||||||||||||||||||||||||||||
| Questions : 9 | What is the sessionStorage Object in html5 ? How to create and access ? | |||||||||||||||||||||||||||||||||||||||||||||
| Answers : 9 | The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. like below we can create and access a sessionStorage here we created “name” as session
<script type=”text/javascript”> sessionStorage.name=”PCDS”; document.write(sessionStorage.name); </script> |
* Header function interview questions
Top header function interview questions and answers
| Questions : 1 | Can we include header fuction in between HTML output of php page | |
| Answers : 1 | No, We can’t use header function in between any out put because it generate error if any out put like any content, white space, line , any tag like < html > etc send before header function so we must use header function befor any Out Put Send. | |
| Questions : 2 | How we can redirect a page to other page or site using php header | |
| Answers : 2 | We can use header function like below to redirect
header(‘Location: http://www.pcds.co.in/’); at place of pcds.co.in we can write any site name or any internal page like header(‘Location: blog.php’); and must there should not any space between Location and : and http status code of this redirection is 302 |
|
| Questions : 3 | How we can do permanent redirect 301 a page to other page or site using php header | |
| Answer : 3 | by below code we can do permanent redirect 301
header(“Location: /blog.php”,TRUE,301); OR header(‘HTTP/1.1 301 Moved Permanently’); header(‘Location: http://www.pcds.co.in/’); |
|
| Questions : 4 | How we can sent HTTP status using header funcion | |
| Answer : 4 | we can send HTTP status by below type of code
header(“HTTP/1.0 404 Not Found”); |
* Database (DBMS) interview questions
Database (DBMS) interview questions and answers are below
| Questions : 1 | What is database or database management systems (DBMS)? and – What’s the difference between file and database? Can files qualify as a database? |
| Answers : 1 |
Database provides a systematic and organized way of storing, managing and retrieving from collection of logically related information. Secondly the information has to be persistent, that means even after the application is closed the information should be persisted. Finally it should provide an independent way of accessing data and should not be dependent on the application to access the information. Main difference between a simple file and database that database has independent way (SQL) of accessing information while simple files do not File meets the storing, managing and retrieving part of a database but not the independent way of accessing data. Many experienced programmers think that the main difference is that file can not provide multi-user capabilities which a DBMS provides. But if we look at some old COBOL and C programs where file where the only means of storing data, we can see functionalities like locking, multi-user etc provided very efficiently. So it’s a matter of debate if some interviewers think this as a main difference between files and database accept it… going in to debate is probably loosing a job. |
| Questions : 2 | What is SQL ? |
| Answers : 2 |
SQL stands for Structured Query Language.SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database.
|
| Questions : 3 | What’s difference between DBMS and RDBMS ? |
| Answers : 3 |
DBMS provides a systematic and organized way of storing, managing and retrieving from collection of logically related information. RDBMS also provides what DBMS provides but above that it provides relationship integrity. So in short we can say RDBMS = DBMS + REFERENTIAL INTEGRITY These relations are defined by using “Foreign Keys” in any RDBMS.Many DBMS companies claimed there DBMS product was a RDBMS compliant, but according to industry rules and regulations if the DBMS fulfills the twelve CODD rules it’s truly a RDBMS. Almost all DBMS (SQL SERVER, ORACLE etc) fulfills all the twelve CODD rules and are considered as truly RDBMS. |
| Questions : 4 | What are CODD rules? |
| Answers : 4 |
In 1969 Dr. E. F. Codd laid down some 12 rules which a DBMS should adhere in order to get the logo of a true RDBMS. Rule 1: Information Rule. “All information in a relational data base is represented explicitly at the logical level and in exactly one way – by values in tables.” Rule 2: Guaranteed access Rule. “Each and every datum (atomic value) in a relational data base is guaranteed to be logically accessible by resorting to a combination of table name, primary key value and column name.” In flat files we have to parse and know exact location of field values. But if a DBMS is truly RDBMS you can access the value by specifying the table name, field name, for instance Customers.Fields [‘Customer Name’]. Rule 3: Systematic treatment of null values. “Null values (distinct from the empty character string or a string of blank characters and distinct from zero or any other number) are supported in fully relational DBMS for representing missing information and inapplicable information in a systematic way, independent of data type.”. Rule 4: Dynamic on-line catalog based on the relational model. “The data base description is represented at the logical level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as they apply to the regular data.”The Data Dictionary is held within the RDBMS, thus there is no-need for off-line volumes to tell you the structure of the database. Rule 5: Comprehensive data sub-language Rule. “A relational system may support several languages and various modes of terminal use (for example, the fill-in-the-blanks mode). However, there must be at least one language whose statements are expressible, per some well-defined syntax, as character strings and that is comprehensive in supporting all the following items Data Definition View Definition Data Manipulation (Interactive and by program). Integrity Constraints Authorization. Transaction boundaries ( Begin , commit and rollback) Rule 6: .View updating Rule “All views that are theoretically updatable are also updatable by the system.” Rule 7: High-level insert, update and delete. “The capability of handling a base relation or a derived relation as a single operand applies not only to the retrieval of data but also to the insertion, update and deletion of data.” Rule 8: Physical data independence. “Application programs and terminal activities remain logically unimpaired whenever any changes are made in either storage representations or access methods.” Rule 9: Logical data independence. “Application programs and terminal activities remain logically unimpaired when information-preserving changes of any kind that theoretically permit un-impairment are made to the base tables.” Rule 10: Integrity independence. “Integrity constraints specific to a particular relational data base must be definable in the relational data sub-language and storable in the catalog, not in the application programs.” Rule 11: Distribution independence. “A relational DBMS has distribution independence.” Rule 12: Non-subversion Rule. “If a relational system has a low-level (single-record-at-a-time) language, that low level cannot be used to subvert or bypass the integrity Rules and constraints expressed in the higher level relational language (multiple-records-at-a-time).” |
| Questions : 5 | What are E-R diagrams? |
| Answers : 5 |
E-R diagram also termed as Entity-Relationship diagram shows relationship between various tables in the database. . |
| Questions : 6 | How many types of relationship exist in database designing? |
| Answers : 6 |
There are three major relationship models:- One-to-one One-to-many Many-to-many |
| Questions : 7 | 7.What is normalization? What are different type of normalization? |
| Answers : 7 |
There is set of rules that has been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization. Benefits of Normalizing your database include: =>Avoiding repetitive entries =>Reducing required storage space =>Preventing the need to restructure existing tables to accommodate new data. =>Increased speed and flexibility of queries, sorts, and summaries. Following are the three normal forms :- First Normal Form For a table to be in first normal form, data must be broken up into the smallest un possible.In addition to breaking data up into the smallest meaningful values, tables first normal form should not contain repetitions groups of fields. Second Normal form The second normal form states that each field in a multiple field primary keytable must be directly related to the entire primary key. Or in other words,each non-key field should be a fact about all the fields in the primary key. Third normal form A non-key field should not depend on other Non-key field. |
| Questions : 8 | What is denormalization ? |
| Answers : 8 |
Denormalization is the process of putting one fact in numerous places (its vice-versa of normalization).Only one valid reason exists for denormalizing a relational design – to enhance performance.The sacrifice to performance is that you increase redundancy in database. |
| Questions : 9 | Can you explain Fourth Normal Form and Fifth Normal Form ? |
| Answers : 9 |
In fourth normal form it should not contain two or more independent multi-v about an entity and it should satisfy “Third Normal form”. Fifth normal form deals with reconstructing information from smaller pieces of information. These smaller pieces of information can be maintained with less redundancy. |
| Questions : 10 | Have you heard about sixth normal form? |
| Answers : 10 |
If we want relational system in conjunction with time we use sixth normal form. At this moment SQL Server does not supports it directly. |
| Questions : 11 | What are DML and DDL statements? |
| Answers : 11 |
DML stands for Data Manipulation Statements. They update data values in table. Below are the most important DDL statements:- =>SELECT – gets data from a database table => UPDATE – updates data in a table => DELETE – deletes data from a database table => INSERT INTO – inserts new data into a database table DDL stands for Data definition Language. They change structure of the database objects like table, index etc. Most important DDL statements are as shown below:- =>CREATE TABLE – creates a new table in the database. =>ALTER TABLE – changes table structure in database. =>DROP TABLE – deletes a table from database => CREATE INDEX – creates an index => DROP INDEX – deletes an index |
| Questions : 12 | How do we select distinct values from a table? |
| Answers : 12 |
DISTINCT keyword is used to return only distinct values. Below is syntax:- Column age and Table pcdsEmp SELECT DISTINCT age FROM pcdsEmp |
| Questions : 13 | What is Like operator for and what are wild cards? |
| Answers : 13 |
LIKE operator is used to match patterns. A “%” sign is used to define the pattern. Below SQL statement will return all words with letter “S” SELECT * FROM pcdsEmployee WHERE EmpName LIKE ‘S%’ Below SQL statement will return all words which end with letter “S” SELECT * FROM pcdsEmployee WHERE EmpName LIKE ‘%S’ Below SQL statement will return all words having letter “S” in between SELECT * FROM pcdsEmployee WHERE EmpName LIKE ‘%S%’ “_” operator (we can read as “Underscore Operator”). “_” operator is the character defined at that point. In the below sample fired a query Select name from pcdsEmployee where name like ‘_s%’ So all name where second letter is “s” is returned. |
| Questions : 14 | Can you explain Insert, Update and Delete query? |
| Answers : 14 |
Insert statement is used to insert new rows in to table. Update to update existing data in the table. Delete statement to delete a record from the table. Below code snippet for Insert, Update and Delete :- INSERT INTO pcdsEmployee SET name=’rohit’,age=’24′; UPDATE pcdsEmployee SET age=’25′ where name=’rohit’; DELETE FROM pcdsEmployee WHERE name = ‘sonia’; |
| Questions : 15 | What is order by clause? |
| Answers : 15 |
ORDER BY clause helps to sort the data in either ascending order to descending order. Ascending order sort query SELECT name,age FROM pcdsEmployee ORDER BY age ASC Descending order sort query SELECT name FROM pcdsEmployee ORDER BY age DESC |
| Questions : 16 | What is the SQL ” IN ” clause? |
| Answers : 16 |
SQL IN operator is used to see if the value exists in a group of values. For instance the below SQL checks if the Name is either ‘rohit’ or ‘Anuradha’ SELECT * FROM pcdsEmployee WHERE name IN (‘Rohit’,'Anuradha’) Also you can specify a not clause with the same. SELECT * FROM pcdsEmployee WHERE age NOT IN (17,16) |
| Questions : 17 | Can you explain the between clause? |
| Answers : 17 | Below SQL selects employees born between ’01/01/1975′ AND ’01/01/1978′ as per mysql SELECT * FROM pcdsEmployee WHERE DOB BETWEEN ’1975-01-01′ AND ’2011-09-28′ |
| Questions : 18 | we have an employee salary table how do we find the second highest from it? |
| Answers : 18 |
below Sql Query find the second highest salary SELECT * FROM pcdsEmployeeSalary a WHERE (2=(SELECT COUNT(DISTINCT(b.salary)) FROM pcdsEmployeeSalary b WHERE b.salary>=a.salary)) |
| Questions : 19 | What are different types of joins in SQL? |
| Answers : 19 |
INNER JOIN Inner join shows matches only when they exist in both tables. Example in the below SQL there are two tables Customers and Orders and the inner join in made on Customers.Customerid and Orders.Customerid. So this SQL will only give you result with customers who have orders. If the customer does not have order it will not display that record. SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON Customers.CustomerID =Orders.CustomerID LEFT OUTER JOIN Left join will display all records in left table of the SQL statement. In SQL below customers with or without orders will be displayed. Order data for customers without orders appears as NULL values. For example, you want to determine the amount ordered by each customer and you need to see who has not ordered anything as well. You can also see the LEFT OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in the next section) if you switch the side of each table. SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID RIGHT OUTER JOIN Right join will display all records in right table of the SQL statement. In SQL below all orders with or without matching customer records will be displayed. Customer data for orders without customers appears as NULL values. For example, you want to determine if there are any orders in the data with undefined CustomerID values (say, after a conversion or something like it). You can also see the RIGHT OUTER JOIN as a mirror image of the LEFT OUTER JOIN if you switch the side of each table. SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID |
| Questions : 20 | What is “CROSS JOIN”? or What is Cartesian product? |
| Answers : 20 |
“CROSS JOIN” or “CARTESIAN PRODUCT” combines all rows from both tables. Number of rows will be product of the number of rows in each table. In real life scenario I can not imagine where we will want to use a Cartesian product. But there are scenarios where we would like permutation and combination probably Cartesian would be the easiest way to achieve it. |
| Questions : 21 | How to select the first record in a given set of rows? |
| Answers : 21 |
Select top 1 * from sales.salesperson |
| Questions : 22 | What is the default “-SORT ” order for a SQL? |
| Answers : 22 |
ASCENDING |
| Questions : 23 | What is a self-join? |
| Answers : 23 |
If we want to join two instances of the same table we can use self-join. |
| Questions : 24 | What’s the difference between DELETE and TRUNCATE ? |
| Answers : 24 |
Following are difference between them: =>>DELETE TABLE syntax logs the deletes thus making the delete operations low. TRUNCATE table does not log any information but it logs information about deallocation of data page of the table. So TRUNCATE table is faster as compared to delete table. =>>DELETE table can have criteria while TRUNCATE can not. =>> TRUNCATE table can not have triggers. |
| Questions : 25 | What’s the difference between “UNION” and “UNION ALL” ? |
| Answers : 25 |
UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the table. , while UNION ALL selects all records from both the tables. |
| Questions : 26 | What are cursors and what are the situations you will use them? |
| Answers : 26 |
SQL statements are good for set at a time operation. So it is good at handling set of data. But there are scenarios where we want to update row depending on certain criteria. we will loop through all rows and update data accordingly. There’s where cursors come in to picture. |
| Questions : 27 | What is ” Group by ” clause? |
| Answers : 27 |
“Group by” clause group similar data so that aggregate values can be derived. |
| Questions : 28 | What is the difference between “HAVING” and “WHERE” clause? |
| Answers : 28 |
“HAVING” clause is used to specify filtering criteria for “GROUP BY”, while “WHERE” clause applies on normal SQL. |
| Questions : 29 | What is a Sub-Query? |
| Answers : 29 |
A query nested inside a SELECT statement is known as a subquery and is an alternative to complex join statements. A subquery combines data from multiple tables and returns results that are inserted into the WHERE condition of the main query. A subquery is always enclosed within parentheses and returns a column. A subquery can also be referred to as an inner query and the main query as an outer query. JOIN gives better performance than a subquery when you have to check for the existence of records. For example, to retrieve all EmployeeID and CustomerID records from the ORDERS table that have the EmployeeID greater than the average of the EmployeeID field, you can create a nested query, as shown: SELECT DISTINCT EmployeeID, CustomerID FROM ORDERS WHERE EmployeeID > (SELECT AVG(EmployeeID) FROM ORDERS) |
| Questions : 30 | What are Aggregate and Scalar Functions? |
| Answers : 30 |
Aggregate and Scalar functions are in built function for counting and calculations. Aggregate functions operate against a group of values but returns only one value. AVG(column) :- Returns the average value of a column COUNT(column) :- Returns the number of rows (without a NULL value) of a column COUNT(*) :- Returns the number of selected rows MAX(column) :- Returns the highest value of a column MIN(column) :- Returns the lowest value of a column Scalar functions operate against a single value and return value on basis of the single value. UCASE(c) :- Converts a field to upper case LCASE(c) :- Converts a field to lower case MID(c,start[,end]) :- Extract characters from a text field LEN(c) :- Returns the length of a text |
| Questions : 31 | Can you explain the SELECT INTO Statement? |
| Answers : 31 |
SELECT INTO statement is used mostly to create backups. The below SQL backsup the Employee table in to the EmployeeBackUp table. One point to be noted is that the structure of pcdsEmployeeBackup and pcdsEmployee table should be same. SELECT * INTO pcdsEmployeeBackup FROM pcdsEmployee |
| Questions : 32 | What is a View? |
| Answers : 32 |
View is a virtual table which is created on the basis of the result set returned by the select statement. CREATE VIEW [MyView] AS SELECT * from pcdsEmployee where LastName = ‘singh’ In order to query the view SELECT * FROM [MyView] |
| Questions : 33 | What is SQl injection ? |
| Answers : 33 |
It is a Form of attack on a database-driven Web site in which the attacker executes unauthorized SQL commands by taking advantage of insecure code on a system connected to the Internet, bypassing the firewall. SQL injection attacks are used to steal information from a database from which the data would normally not be available and/or to gain access to an organization’s host computers through the computer that is hosting the database. SQL injection attacks typically are easy to avoid by ensuring that a system has strong input validation. As name suggest we inject SQL which can be relatively dangerous for the database. Example this is a simple SQL SELECT email, passwd, login_id, full_name FROM members WHERE email = ‘x’ Now somebody does not put “x” as the input but puts “x ; DROP TABLE members;”. So the actual SQL which will execute is :- SELECT email, passwd, login_id, full_name FROM members WHERE email = ‘x’ ; DROP TABLE members; Think what will happen to your database. |
| Questions : 34 | What is Data Warehousing ? |
| Answers : 34 |
Data Warehousing is a process in which the data is stored and accessed from central location and is meant to support some strategic decisions. Data Warehousing is not a requirement for Data mining. But just makes your Data mining process more efficient. Data warehouse is a collection of integrated, subject-oriented databases designed to support the decision-support functions (DSF), where each unit of data is relevant to some moment in time. |
| Questions : 35 | What are Data Marts? |
| Answers : 35 |
Data Marts are smaller section of Data Warehouses. They help data warehouses collect data. For example your company has lot of branches which are spanned across the globe. Head-office of the company decides to collect data from all these branches for anticipating market. So to achieve this IT department can setup data mart in all branch offices and a central data warehouse where all data will finally reside. |
| Questions : 36 | What are Fact tables and Dimension Tables ? What is Dimensional Modeling and Star Schema Design |
| Answers : 36 |
When we design transactional database we always think in terms of normalizing design to its least form. But when it comes to designing for Data warehouse we think more in terms of denormalizing the database. Data warehousing databases are designed using Dimensional Modeling. Dimensional Modeling uses the existing relational database structure and builds on that. There are two basic tables in dimensional modeling:- Fact Tables. Dimension Tables. Fact tables are central tables in data warehousing. Fact tables have the actual aggregate values which will be needed in a business process. While dimension tables revolve around fact tables. They describe the attributes of the fact tables. |
| Questions : 37 | What is Snow Flake Schema design in database? What’s the difference between Star and Snow flake schema? |
| Answers : 37 |
Star schema is good when you do not have big tables in data warehousing. But when tables start becoming really huge it is better to denormalize. When you denormalize star schema it is nothing but snow flake design. For instance below customeraddress table is been normalized and is a child table of Customer table. Same holds true for Salesperson table. |
| Questions : 38 | What is ETL process in Data warehousing? What are the different stages in “Data warehousing”? |
| Answers : 38 |
ETL (Extraction, Transformation and Loading) are different stages in Data warehousing. Like when we do software development we follow different stages like requirement gathering, designing, coding and testing. In the similar fashion we have for data warehousing. Extraction:- In this process we extract data from the source. In actual scenarios data source can be in many forms EXCEL, ACCESS, Delimited text, CSV (Comma Separated Files) etc. So extraction process handle’s the complexity of understanding the data source and loading it in a structure of data warehouse. Transformation:- This process can also be called as cleaning up process. It’s not necessary that after the extraction process data is clean and valid. For instance all the financial figures have NULL values but you want it to be ZERO for better analysis. So you can have some kind of stored procedure which runs through all extracted records and sets the value to zero. Loading:- After transformation you are ready to load the information in to your final data warehouse database. |
| Questions : 39 | What is Data mining ? |
| Answers : 39 |
Data mining is a concept by which we can analyze the current data from different perspectives and summarize the information in more useful manner. It’s mostly used either to derive some valuable information from the existing data or to predict sales to increase customer market. There are two basic aims of Data mining:- Prediction: – From the given data we can focus on how the customer or market will perform. For instance we are having a sale of 40000 $ per month in India, if the same product is to be sold with a discount how much sales can the company expect. Summarization: - To derive important information to analyze the current business scenario. For example a weekly sales report will give a picture to the top management how we are performing on a weekly basis? |
| Questions : 40 | Compare Data mining and Data Warehousing ? |
| Answers : 40 |
“Data Warehousing” is technical process where we are making our data centralized while “Data mining” is more of business activity which will analyze how good your business is doing or predict how it will do in the future coming times using the current data. As said before “Data Warehousing” is not a need for “Data mining”. It’s good if you are doing “Data mining” on a “Data Warehouse” rather than on an actual production database. “Data Warehousing” is essential when we want to consolidate data from different sources, so it’s like a cleaner and matured data which sits in between the various data sources and brings then in to one format. “Data Warehouses” are normally physical entities which are meant to improve accuracy of “Data mining” process. For example you have 10 companies sending data in different format, so you create one physical database for consolidating all the data from different company sources, while “Data mining” can be a physical model or logical model. You can create a database in “Data mining” which gives you reports of net sales for this year for all companies. This need not be a physical database as such but a simple query. |
| Questions : 41 | What are indexes? What are B-Trees? |
| Answers : 41 |
Index makes your search faster. So defining indexes to your database will make your search faster.Most of the indexing fundamentals use “B-Tree” or “Balanced-Tree” principle. It’s not a principle that is something is created by SQL Server or ORACLE but is a mathematical derived fundamental.In order that “B-tree” fundamental work properly both of the sides should be balanced. |
| Questions : 42 | I have a table which has lot of inserts, is it a good database design to create indexes on that table?Insert’s are slower on tables which have indexes, justify it?or Why do page splitting happen? |
| Answers : 42 |
All indexing fundamentals in database use “B-tree” fundamental. Now whenever there is new data inserted or deleted the tree tries to become unbalance. Creates a new page to balance the tree. Shuffle and move the data to pages. So if your table is having heavy inserts that means it’s transactional, then you can visualize the amount of splits it will be doing. This will not only increase insert time but will also upset the end-user who is sitting on the screen. So when you forecast that a table has lot of inserts it’s not a good idea to create indexes. |
| Questions : 43 | What are the two types of indexes and explain them in detail? or What’s the difference between clustered and non-clustered indexes? |
| Answers : 43 |
There are basically two types of indexes:- Clustered Indexes. Non-Clustered Indexes. In clustered index the non-leaf level actually points to the actual data.In Non-Clustered index the leaf nodes point to pointers (they are rowid’s) which then point to actual data. |