PHP MySQL Questionnare part-1

Posted on: October 26, 2008

1. Which of the following is not valid PHP code?
A. $_10
B. ${“MyVar”}
C. &$something
D. $10_somethings
E. $aVaR

Answer: PHP variables always start with a dollar sign and are a sequence of characters and numbers within the Latin alphabet, plus the underscore character. ${“MyVar”} is a valid variable name that simply uses a slightly less common naming convention, while &$something is a reference to the $something variable. Variables, however cannot start with numbers, making $10_somethings invalid and Answer D correct.

2. Which language construct can best represent the following series of if conditionals?
if($a == ‘a’) {
} else if ($a == ‘b’) {
} else if ($a == ‘c’) {
} else {
A. A switch statement without a default case
B. A recursive function call
C. A while statement
D. It is the only representation of this logic
E. A switch statement using a default case

Answer: A series of if…else if code blocks checking for a single condition as above is a perfect place
to use a switch statement:
switch($a) {
case ‘a’:
case ‘b’:
case ‘c’:
Because there is a catch-all else condition, a default case must also be provided for that
situation. Answer E is correct.

3. What is the best way to iterate through the $myarray array, assuming you want to modify the value of each element as you do?
$myarray = array (“My String”, “Another String”, “Hi, Mom!”);
A. Using a for loop
B. Using a foreach loop
C. Using a while loop
D. Using a do…while loop
E. There is no way to accomplish this goal

Answer: Normally, the foreach statement is the most appropriate construct for iterating through an array. However, because we are being asked to modify each element in the array, this option is not available, since foreach works on a copy of the array and would therefore result in added overhead. Although a while loop or a do…while loop might work, because the array is sequentially indexed a for statement is best suited for the task, making Answer A correct:
$myarray = array (“My String”, “Another String”, “Hi, Mom!”);
for($i = 0; $i < count($myarray); $i++)
$myarray[$i] .= ” ($i)”;

4. How can a script come to a clean termination?
A. When exit() is called
B. When the execution reaches the end of the current file
C. When PHP crashes
D. When Apache terminates because of a system problem

Answer: The only answer that really fits the bill is A. A script doesn’t necessarily terminate when it reaches the end of any file other than the main one—so the “current” file could be externally included and not cause the script to terminate at its end. As far as PHP and Apache crashes, they can hardly be considered “clean” ways to terminate a script.

5. Which object-oriented pattern would you use to implement a class that must be instantiated only once for the entire lifespan of a script?
A. Model-view-controller
B. Abstract factory
C. Singleton
D. Proxy
E. State
Answer: The Singleton Pattern is handy whenever only one instance of a particular class can exist at any given time (and, yes, in case you’re wondering, you should expect the exam to test you on the basics of patterns, too).

6. Assume that a class called testclass is defined. What must the name of its constructor method be?
A. __construct
B. initialize
C. testclass
D. __testclass
E. Only PHP 5 supports constructors
Answer: Although PHP 5 has “unified” constructors (__construct()), in PHP 4 constructors are always methods whose name matches the class name. This means that, for a class called testclass, the constructor is Answer C, testclass().

7. How would you call the mymethod method of a class within the class itself?
A. $self=>mymethod();
B. $this->mymethod();
C. $current->mymethod();
D. $this::mymethod();
E. None of the above are correct

Answer: In PHP, methods and properties of a class’ current instance are accessed from within its methods using the $this special variable. Answer B, therefore, is correct.

8. How can the index.php script access the email form element of the following HTML form? (Choose 2)
<form action=”index.php” method=”post”>
<input type=”text” name=”email”/>
A. $_GET[’email’]
B. $_POST[’email’]
C. $_SESSION[‘text’]
D. $_REQUEST[’email’]
E. $_POST[‘text’]

Answer: Since the form’s method is post, the script will only be able to read the value through the $_POST and $_REQUEST superglobal arrays. The element’s name (email) is used as the key for the value in the array and, therefore, Answers B and D are correct. Note that, although perfectly valid from a logical perspective, the use of $_REQUEST should be discouraged because of potential security implications.

9. By default, PHP stores session data in ________________.
A. The filesystem
B. A database
C. Virtual memory
D. Shared memory
E. None of the above
Answer: The filesystem (Answer A). By default, PHP stores all session information in the /tmp folder; users of operating systems where this folder doesn’t exist (such as Windows) must change the default value of the session.save_path php.ini setting to a directory appropriate for their setup (e.g.: C:\Temp).

10. The ___________ function automatically transforms newline characters into HTML <br /> tags
Answer: This identifies the nl2br function, which can be used precisely for this purpose.

11. Array values are keyed by ______ values (called indexed arrays) or using ______ values (called associative arrays). Of course, these key methods can be combined as well.
A. Float, string
B. Positive number, negative number
C. Even number, string
D. String, Boolean
E. Integer, string
Answer: Arrays that are keyed by integer values are called indexed arrays, while those keyed by strings are called associative arrays. The correct answer is, therefore, E.

12. What is the name of a function used to convert an array into a string?
Answer: The serialize function takes a complex data structure and returns a string that can later be used by the unserialize function to reconstruct the original data structure. A valid answer to this question could also be the implode function, which concatenates each element of an array with a “glue” string.

13. What will the following script output?
$array = array (‘3’ => ‘a’, ‘1b’ => ‘b’, ‘c’, ‘d’);
echo ($array[1]);
A. 1
B. b
C. c
D. A warning.
E. a
Answer: PHP starts assigning numeric keys to elements without a hard-coded key from the lowest numeric key available (even if that key is a numeric string). If you never specify a numeric key to start with, it starts from zero. In our script, however, we assigned the key ‘3’ to the very first element, thus causing the interpreter to assign the key 4 to the third element and 5 to the last element. Note that the key ‘1b’ is not considered numeric, because it doesn’t
evaluate to an integer number. Therefore, element 1 doesn’t exist, and Answer D is correct.

14. What will the following script output?
$array = array (0.1 => ‘a’, 0.2 => ‘b’);
echo count ($array);
A. 1
B. 2
C. 0
D. Nothing
E. 0.3
Answer: The script will output 1 (Answer A). This is because only integer numbers and strings can be used as keys of an array—floating-point numbers are converted to integers. In this case, both 0.1 and 0.2 are converted to the integer number 0, and $array will only contain the element 0 => ‘b’.

15. What elements will the following script output?
$array = array (true => ‘a’, 1 => ‘b’);
var_dump ($aray);
A. 1 => ‘b’
B. True => ‘a’, 1 => ‘b’
C. 0 => ‘a’, 1 => ‘b’
D. None
E. It will output NULL
Answer: This question tries to attract your attention to a problem that doesn’t bear on its answer. The $array array will contain only one element, since true evaluates to the integer 1. However, there is a typo in the var_dump() statement—$array is misspelled as $aray, using only one ‘r’. Therefore, the var_dump() statement will output NULL (and, possibly, a notice, depending on your error settings). Answer E is correct.

16. What is the best all-purpose way of comparing two strings?

A. Using the strpos function
B. Using the == operator
C. Using strcasecmp()
D. Using strcmp()
Answer: Answer E is correct—strcmp() offers the safest comparison mechanism between two strings. Note that Answer C is incorrect because strcasecmp() is not an “all-purpose” function, since it performs a case-insensitive comparison.

17. What will the following script output?
echo ‘Testing ‘ . 1 + 2 . ’45’;
A. Testing 1245
B. Testing 345
C. Testing 1+245
D. 245
E. Nothing
Answer: This question tests your knowledge of string manipulation and operator precedence. The concatenation operator has a higher precedence than the addition operator. Therefore, PHP will interpret this expression as if it were written as (‘Testing ‘ . 1) + (2 . ’45’). When the addition takes place, the first concatenation is evaluated as the integer zero, since the string Testing 1 is not a valid number. The second concatenation is evaluated as the number 245
and, therefore, PHP outputs the result of 0 + 245, that is, 245. Therefore, Answer D is correct.

18. What will be the output of the following script?
$s = ‘12345’;
$s[$s[1]] = ‘2’;
echo $s;
A. 12345
B. 12245
C. 22345
D. 11345
E. Array
Answer: Since strings can be addressed as arrays, this script simply replaces the value of the second characters (identified by $s[1]) with the character 2, resulting in the string 12245 being printed out. Answer B is correct.

19. Which of the following comparisons will return True? (Choose 2)
A. ‘1top’ == ‘1’
B. ‘top’ == 0
C. ‘top’ === 0
D. ‘a’ == a
E. 123 == ‘123’
Answer: Answers B and E are correct. In Answer B, the string top is evaluated to integer zero when the comparison takes place and, since the == operator does not perform strict type checking, it returns True. In answer E, the same thing happens to the string 123, which is evaluated to the integer number 123, thus resulting in a successful comparison.

20. What will the following script output?
$time = strtotime (‘2004/01/01’);
echo date (‘H:\i:s’, $time);
A. 00:00:00
B. 12:00:00
C. 00:i:00
D. 12:i:00
E. -1
Answer: The H and s parameters in the string specification passed to date() indicate the hour in 24- hour format and the seconds. Since the i is actually escaped with a backslash, it will be considered a literal and printed as such. Also, the fact that no particular time was specified in the call to strtotime() will cause the function to default to midnight. Therefore, the final output of the script will be 00:i:00, which corresponds to Answer C.

21. What function name should replace the question marks in the following script?
for ($i = 0; $i < 100; $i++) {
$day = rand (1, 31);
$month = rand (1, 12);
$year = rand (1000, 2500);
if (????????? ($month, $day, $year)) {
echo “$month/$day/$year is a valid date\n”;
} else { echo “$month/$day/$year is not a valid date\n”; }
A. date()
B. strftime()
C. microtime()
D. checkdate()
E. mktime()
Answer: The checkdate function can be used to verify if a Gregorian date is valid (although with some limitations—October 5-14, 1582, for example, are accepted as valid dates even though they do not exist in the calendar). Therefore, since this script essentially tries to create random dates and then determine if they are right, Answer D is correct.

22. Which of the following definitions describes the time function?
A. It returns the number of seconds since the UNIX epoch
B. It returns the number of seconds since the UNIX epoch expressed according to the GMT time zone
C. It returns the number of seconds since the UNIX epoch expressed according to the local time zone
D. It calculates the time elapsed since the UNIX epoch and expresses it as an integer number
E. All of the above

Answer: Answer E is correct. Clearly, time() calculates the number of seconds since the epoch and, since both Answer A and Answer D express that very same concept, they are obviously correct. Answers B and C are a bit less immediate, but they really mean the same thing. The number of seconds since the epoch is the same, regardless of whether you express it in the local time zone or in GMT, since the epoch itself is a fixed point in time. It is only when you need to convert the integer into human-readable format that you must consider the representation most appropriate for any given time zone. Therefore, Answers B and C are also correct. This may sound like a bit of a trick question, but it’s really testing whether you understand the difference between absolute and relative time—a very important concept when dealing with dates.

23. Which of the following functions do not return a timestamp? (Choose 2)
A. time()
B. date()
C. strtotime()
D. localtime()
E. gmmktime()
Answer: Answers B and D are correct. The date function returns a string, while localtime() returns an array.

24. Which one of the following is not a valid e-mail address?
B. “John Coggeshall” <>
C. joe @
D. jean-có
E. john

Answer: Of all of the e-mail addresses listed above, only Answer D is invalid. Both A and B are classic e-mail addresses that are in use frequently today. Although C looks invalid, mail transport agents (MTAs) automatically remove extra whitespace, making it just as good, while E is valid for a local delivery. This leaves D, which contains an invalid character for an e-mail address (an accented letter).

25. Consider the following SQL statement. Which of the following could be good ideas for limiting the amount of data returned by it? (Choose 2)
A. If possible, convert the query to a stored procedure
B. If possible within your application, reduce the number of fields retrieved by the query by specifying each field individually as part of the query
C. If possible, add a WHERE clause
D. If supported by the DBMS, convert the query to a view
E. If the DBMS allows it, use prepared statements

Answer: The two best tips for optimizing this query are, if possible, to limit the amount of data extracted by it by adding a WHERE clause and specifying the exact fields you want extracted from it. In general, unless otherwise dictated by the circumstances, you should not use SELECT *, both because of the waste of data and because it exposes your application to problems arising from changes in the database structure. This makes answers B and C correct.

26. The dataset returned by a query can be filtered by adding a ________ clause to it.
Answer: Queries can be filtered in a number of ways, but it’s clear here that the question asks about filtering performed on the dataset to be returned by a query and, therefore, the WHERE clause is the correct answer.

27. The ___________ statement can be used to add a new row to an existing table.
Answer: The INSERT statement is, obviously the correct answer.

28. In how many ways we can retrieve the data in the result set of MySQL using PHP?
Answer: You can do it by 4 Ways
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

29. How can we create a database using PHP and MySQL?
Answer: We can create MySQL database with the use of mysql_create_db(“Database Name”)

30. What are the current versions of apache, PHP, and MySQL?
Answer: the current versions are
PHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4
[ Note: visit,, to get current versions. ]

31. How can we get the browser properties using PHP?
Answer: By using $_SERVER[‘HTTP_USER_AGENT’] variable.

32. How can we destroy the cookie?
Answer: By setting the cookie in past.

33. What are the other commands to know the structure of table using MySQL commands except explain command?
Answer: describe table_name

34. How can we find the number of rows in a table using MySQL?
Answer: SELECT COUNT(*) FROM table_name;

35. Consider the following code fragment and answer the question
$variable = ‘hello’;
$$variable = ‘world’;
Would this code produce any errors? What variables are defined after this code is run?
Answer: Yes this code will run successfully. In this case a variable will be declared named $hello which will hold the value ‘world’

36. What do people mean when they describe HTTP as being “stateless”? How can web developers introduce state on a stateless medium?
Answer: HTTP forget everything when it is being refreshed. This is why it is known as stateless protocall. We can overcome it by using PHP’s SESSION and COOKIE super global arrays.

37. Are you familiar with the MVC design pattern? Demonstrate your understanding by briefly describing it.

38. Is it possible to upload files using XMLHttpRequest?
Answer: Yes, it is possible.

39. Which design pattern is used in CakePHP?
A. Singleton
C. Factory
Answer: CakePHP uses MVC design pattern.

40. Who is the father of jQuery?
Answer: John Resig

41. How can you write comments in PHP?
Answer: In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

42. What is the full meaning of Ajax?
Answer: Asynchronous JavaScript and XML

43. What is subversion?
Answer: Your Answer: Subversion (SVN) is a version control system initiated in 2000 by CollabNet Inc. It is used to maintain current and historical versions of files such as source code, web pages, and documentation. Its goal is to be a mostly-compatible successor to the widely used Concurrent Versions System (CVS).

44. What type of database used in Joomla?
Answer: MySQL

45. Define “Script kiddie”.
Answer: Your Answer:Script kiddies are crackers that exploit and deface web sites and message boards for fun and bragging rights. Sometimes, script kiddies can cause lots of damage. As a message board administrator, you should secure your board as if you are under constant threat from script kiddies and other, more sophisticated, threats, because you are.

46. Define “Forum”
Answer: An organizational area for posts on your message board with a common theme.

47. Write code to connect with a MySQL database in PHP using mysql_connect() where
Answer: mysql_connect(‘localhost’, ‘user’, ‘pass’);

48. Write the syntax of PHP’s mail().
Answer: bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters]] )

49. What is the purpose of PHP’s trim().
Answer: Strip whitespace (or other characters) from the beginning and end of a string

50. Which of the following tags is not a valid way to begin and end a PHP code block?
A. <% %>
B. <? ?>
C. <?= ?>
D. <! !>
E. <?php ?>

Answer: While tags such as <% %> and <?= ?> are often forgotten in PHP programming, they are valid
ways to delimit a PHP code block. The <! and !> tags, however, are not valid and, therefore, the correct answer is D. Keep in mind, in any case, that some of these tags are not always available, depending on how the php.ini file on which the PHP interpreter runs is configured.

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

I am Nurul Ferdous a Zend Certified Engineer (ZCE), serving at Bangladesh Internet Press Limited (BIPL) as programmer. I am a FOSS advocate and love RnD.


Me @ LinkedIn

View Nurul Ferdous's profile on LinkedIn

My Photos @ Flickr

Blog Stats

  • 42,882 [ Vistors ]

My Twitter Updates

%d bloggers like this: