Thursday, December 10, 2009

Php Mysql Question

Ques. How can I set the time zone for MySQL to UK time?
Ans. You can also set environment variables in my.cnf; In the data (normally var) directory.

Ques. How do I set the browser timeout?
Ans. If your script is too complex to finish within the standard 30 seconds you can set a new value with the function: set_time_limit(900); this sets the timeout too 900 seconds / 15 minutes.

Ques. How to count number of parameters given in URL by POST?
Ans. echo count ($HTTP_POST_VARS); Or count($_POST)

Ques. How do I check whether a string contains HTML?
Ans. There are two ways you can do it, one is using a regular expression the other is comparing strings.
First the regular expression approach:
if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $string)) {
echo "string contains html";
}
And here is the other approach:
if(strlen($string) != strlen(strip_tags($string)){
echo "string contains HTML";
}
Ques. What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

Ques. How can we know the number of days between two given dates using PHP?
$date1 = date('Y-m-d'); $date2 = '2006-07-01'; $days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
OR:
$dateparts1=explode('-', $strDate);
$dateparts2=explode('-', $currDate);
$start_date=@gregoriantojd($dateparts1[1], $dateparts1[2], $dateparts1[0]);
$end_date=@gregoriantojd($dateparts2[1], $dateparts2[2], $dateparts2[0]);
$dateDiff = $end_date-$start_date;

As per Php manual, strtotime() only works date upto 2038.

Ques. What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
* Temporary cookies can not be used for tracking long-term information.
* Persistent cookies can be used for tracking long-term information.
* Temporary cookies are safer because no programs other than the browser can access them.
* Persistent cookies are less secure because users can open cookie files see the cookie values.

Ques. When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.

Ques. How do you call a constructor for a parent class?
parent::constructor($value)

Ques. How can we encrypt and decrypt a data presented in a table using MySQL?
You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:
AES_ENCRYPT(str, key_str); AES_DECRYPT(crypt_str, key_str)

Ques. How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

Ques. What are the functions for IMAP?
imap_body - Read the message body
imap_check - Check current mailbox
imap_delete - Mark a message for deletion from current mailbox
imap_mail - Send an email message

Ques. What is DDL, DML and DCL ?
If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.

Ques. You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user?

SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10;
SELECT FOUND_ROWS();

The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase “Found 13,450,600 results, displaying 1-10″. Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.

Ques. How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
Ques. What does –i-am-a-dummy flag to do when starting MySQL?
Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

Ques. When would you use ORDER BY in DELETE statement?
When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

Ques. How can you see all indexes defined for a table?
SHOW INDEX FROM techpreparation_questions;

Ques. How would you change a column from VARCHAR(10) to VARCHAR(50)?
ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

Ques. How would you delete a column?
ALTER TABLE techpreparation_answers DROP answer_user_id.

Ques. How would you change a table to InnoDB?
ALTER TABLE techpreparation_questions ENGINE innodb;

Ques. When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?
1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column

Ques. What’s the difference between CHAR_LENGTH and LENGTH?
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.

Ques. How do you convert a string to UTF-8?
SELECT (techpreparation_question USING utf8);

Ques. What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.

Ques. What does + mean in REGEXP?
At least one character.

Ques. What’s the difference between Unix timestamps and MySQL timestamps?
Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.

Ques. How do you convert between Unix timestamps and MySQL timestamps?
UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.

Ques. Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

Ques. Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.

Q.Is it possible to set a time expire page in PHP.?
Yes it is
Using header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
?>

Q.How can we SAVE an image from a remote
web Server to my web server using PHP?
$file_rimg = fopen(“http://w3answers /image23.jpg”,’rb’);
$newfile_name_img = “/tmp/tutorial.file”;
$file_wnew = fopen($newfile_name_img,’wb’);
while (!feof($file_rimg)) {
$chunk_rd = fread($file_rimg,1024);
fwrite($file_wnew,$chunk_rd);
}
fclose($file_wnew);
fclose(file_rimg);
?>

Q.What is the output of 2^2 in php ?
The answer is 0 (Zero)
Important note
Everyone expected answer would be 4. But answer is zero. How it happened only in php ?
The ^ operator is different in each language.In PHP ^ means the bitwise exlusive or of the two numbers.

Q.What is the output of below script?
$x = 3;
switch ($x) {
case 2: echo ‘line 1′; break;
case 3:
case 4: echo ‘line 2′; break;
default: echo ‘line 3′;
}
?>
a. echo ‘line 3′; b. echo ‘line 2′; c. Error d. None of the above
Ans: b (Answer is line2)

Q.What is the output here?
$x = ‘raj’;
echo ‘Hello $x’;
?>
a. helloravj b. Parse error c. hello $x d. syntax error
ANS: c

Q.What output do you get here?
$list = array(“block”,”cut”,”pens”,”dogs”);
$list[] = “elephant”;
$list[] = “dragon”;
print “$list[4]“;
?>
a. Error b. elephant c. dragon d. nothing e. dogs
ANS: b (elephant)
Q. what is the output for following code?
echo 12+FALSE;
?>
Q. 12 b. no c. parse error d. T_ECHO error e. FALSE
ANS: 12

Q.What is the output ?
$x=7;
if ($x < 2) { echo “11″; }
elseif ($x < 16) { echo “12″; }
elseif ($x < 14) { echo “13″; }
elseif ($x > 14) { echo “14″; }
elseif ($x < 10) { echo “15″; }
else { echo “16″; }
?>
a.16 b.15 c.12 d.13
ANS:12

Q.What is the result here?
echo “test”;
$x = ”;
switch ($x) {
case “0″: echo “String”; br;
case 0: echo “”; break;
case NULL: echo “NULL”; br;
case FALSE: echo “heeder”; br;
case “”: echo “no string”; br;
default: echo “nothing else”; br;
}
?>
a. Something else b. Empty string c. Integer d. String
ANS: Integer
Q.What is the output?
function x ($y) {
function y ($z) {
return ($z*2); }
return($y+3); }
$y = 4;
$y = x($y)*y($y);
echo “$y”;
?>
a. None b. 54 c. 56 d. 58
ANS:56
Ques. how to track user logged out or not? when user is idle ?
By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.
The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.
Ques. 1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

Ques. what is garbage collection? default time ? refresh time?
Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.
There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100

Ques. PHP how to know user has read the email?
Using Disposition-Notification-To: in mailheader we can get read receipt.
Add the possibility to define a read receipt when sending an email.
It’s quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at ‘createHeader’ function add:
if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

Ques. default session time ?
default session time in PHP is 1440 seconds or 24 minutes.

Ques. default session save path ?
Default session save path id temporary folder /tmp

Ques. how to track user logged out or not? when user is idle ?
By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.
The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

Ques. what is design pattern? singleton pattern?
A design pattern is a general reusable solution to a commonly occurring problem in software design.
The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

Ques. what are magic methods?
Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone

Ques. diff b/w php4 & php5 ? In PHP5
1. 1 Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument

3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constuctor and __destructor function
5. __autoload function for dynamically including certain include files depending on the class you are trying to create.
6. 6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.
7. Interfaces & Abstract Classes
8. Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.
9. An __clone method if you really want to duplicate an object

Ques. what is cross site scripting? SQL injection?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.
SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

Ques. what is the major php security hole? how to avoid?
1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first.
2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes!
3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. If you don’t want the file contents to be seen, give the file a .php extension.

Ques. HOW we can transfer files from one server to another server without web forms?
using CURL we can transfer files from one server to another server. ex:
Uploading file
/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */
$ch = curl_init();
$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);
curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php’);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch); ?>
output:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 ) )
Ques. using CSS can we have a scroll to table?
No table won't support scrolling of its data. but we can do another workaround like placing a table
in a DIV layer and setting the DIV css property to overflow:auto will do that
Ques. Difference b/w OOPS concept in php4 and PHP5 ?
version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of object oriented programming (OOP) were offered in version 4, several deficiencies existed, including:
• An unorthodox object-referencing methodology
• No means for setting the scope (public, private, protected, abstract) of fields and methods
• No standard convention for naming constructors
• Absence of object destructors
• Lack of an object-cloning feature
• Lack of support for interfaces

Ques. how to set session time out at run time or how to extend the session timeout at runtime?
// Get the current Session Timeout Value
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);
Change the Session Timeout Value
// Change the session timeout value to 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);
Sorting function attributes

No comments:

Post a Comment