Tuesday, August 18, 2009

PHP Mysql Interview Questions and Answers

What are the differences between Get and post methods in form submitting. give the case where we can use get and we can use post methods?

When to use GET or POST
The HTML 2.0 specification says, in section Form Submission (and the HTML 4.0 specification repeats this with minor stylistic changes):
–>If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.
–>If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

How the form data is transmitted? quotation from the HTML 4.0 specification
–> If the method is “get” – -, the user agent takes the value of action, appends a ? to it, then appends the form data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype attribute. Quote from CGI FAQ

Firstly, the the HTTP protocol specifies differing usages for the two methods. GET requests should always be idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more identical requests will have no further effect.

This is a theoretical point which is also good advice in practice. If a user hits “reload” on his/her browser, an identical request will be sent to the server, potentially resulting
in two identical database or guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is usually the case with CGI output), but will typically prompt the user before re-submitting a POST request. This means you’re far less likely to get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for idempotent operations, such as querying a database, though it matters little if you’re using a form. There is a further practical constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params) approaches or exceeds 1Kb, you are well-advised to use POST in any case.

I would prefer POST when I don’t want the status to be change when user resubmits. And GET
when it does not matter.

Who is the father of PHP and explain the changes in PHP versions?
Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additionalOOP features

How can we submit a form without a submit button?
The main idea behind this is to use Java script submit() function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit() method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites).

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

What is the difference between mysql_fetch_object and mysql_fetch_array?
A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

What is the difference between $message and $$message?
It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.

How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’ using regular expression of PHP?
preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found); echo $found[1];

can we create a database using PHP and MySQL?
can create MySQL database with the use of mysql_create_db(“Database Name”)

What are the differences between require and include, include_once and require_once?
The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handle
failure. include() produces a Warning while require() results in a Fatal Error. In other words, use
require() if you want a missing file to halt processing of the page.
include() does not behave this way, the script will continue regardless.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function
redefinitions, variable value reassignments, etc.

require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
Yes we can use include() more than one time in any page though it is not a very good practice.
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax: create table employee (eno int(2),ename varchar(10)) ?
can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM and etc..
MyISAM is the default storage engine as of MySQL 3.23 and as a result if we do not specify the table name explicitly it will be assigned to the default engine.

Functions in IMAP, POP3 AND LDAP?
You can find these specific information in PHP Manual.


How can I execute a PHP script using command line?
As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program. Be aware that if your PHP script was written for the Web CGI interface,
it may not execute properly in command line environment.

Suppose your Zend engine supports the mode Then how can u configure your PHP Zend engine to support mode ?
In php.ini file:
set
short_open_tag=on
to make PHP support

Shopping cart online validation i.e. how can we configure Paypal, etc.?
We can find the detail documentation about different paypal integration process at the following site
PayPal PHP
SDK : http://www.paypaldev.org

What is meant by nl2br()?
HTML line breaks () before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines. For example: echo nl2br(”god bless\n you”) will output “god
bless you” to your browser.

Draw the architecture of Zend engine?
The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an abbreviation of their names. In the early days of PHP4, it worked as follows:
The PHP script was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level binary instructions. Then the opcode was executed and the HTML generated sent to the client. The opcode was flushed from memory after execution. Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show the how modern PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.

What are the current versions of apache, PHP, and MySQL?
As of February, 2007 the current versions arePHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4Note: visit www.php.net,

http://dev.mysql.com/downloads/mysql/,
www.apache.org to get current
versions.

What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and operating systems?
A:19 All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language.

How can we encrypt and decrypt a data present in a MySQL table using MySQL?
AES_ENCRYPT () and AES_DECRYPT ()

How can we encrypt the username and password using PHP?
The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

What are the features and advantages of object-oriented programming?
One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system

What are the differences between procedure-oriented languages and object-oriented languages?
Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can affect any code that follows it. If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc).
If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.Object-Oriented programming takes a radically different approach:Code and data are merged into one indivisible item – an object (the term “component” has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around “date”) The object would contain all information and
functionality for that thing (A date object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system. The information within an object is encapsulated (or hidden) from the
rest of the system. A system is composed of multiple objects (i.e., date function, reports,
order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called
messages and each object has an interface that manages messages. OO programming languages include features such as “class”, “instance”, “inheritance”, and “polymorphism” that increase the power and flexibility of an object.

What is the use of friend function?
Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.
A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
What are the differences between public, private, protected, static, transient, final and volatile?
Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines the item.
Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
transient: A transient variable is a variable that may not be serialized.
volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at
any time.
Q:26 What are the different types of errors in PHP?
A:26 Three are three types of errors:1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default,such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors – for example,
instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.
Q:27 What is the functionality of the function strstr and stristr?
A:27 strstr:
Returns part of haystack string from the first occurrence of needle to the end of haystack.If needle is not found,
returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This function is case-sensitive. For case-insensitive searches, use stristr().
Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?
A:28 Please read the release notes at http://www.php.net.
Q:29 How can we convert asp pages to PHP pages?
A:29 there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available at http://asp2php.naken.cc./
Q:30 What is the functionality of the function htmlentities?
A:30 Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
Q:31 How can we get second of the current time using date function?
A:31 $second = date(”s”);
Q:32 How can we convert the time zones using PHP?
A:32 By using date_default_timezone_get and date_default_timezone_set function on PHP 5.1.0
', date(DATE_RFC1123, $stamp) ,'
';?>
Q:33 What is meant by urlencode and urldocode?
A:33 URLencode returns a string in which all non-alphanumeric characters
except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string.
Q:34 What is the difference between the functions unlink and unset?
A:34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.
Q:35 How can we register the variables into a session?
A:35 $_SESSION[’name’] = “Mizan”;
Q:36 How can we get the properties (size, type, width, height) of an image using PHP image functions?
A:36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t
Q:37 How can we get the browser properties using PHP?
A:37 By using
$_SERVER['HTTP_USER_AGENT']
variable.
Q:38 What is the maximum size of a file that can be uploaded using PHP and how can we change this?
A:38 By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M
Q:39 How can we increase the execution time of a PHP script?
A:39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds
Q:40 How can we take a backup of a MySQL table and how can we restore it. ?
A:40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
Q:41 How can we optimize or increase the speed of a MySQL select query?
A:41
* first of all instead of using select * from table1, use select
column1, column2, column3.. from table1
* Look for the opportunity to introduce index in the table you are querying.
* use limit keyword if you are looking for any specific number of rows from the result set.
Q:42 How many ways can we get the value of current session id?
A:42 session_id() returns the session id for the current session.
Q:43 How can we destroy the session, how can we unset the variable of a session?
A:43 session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables
Q:44 How can we destroy the cookie?
A:44 Set the cookie in past.
Q:45 How many ways we can pass the variable through the navigation between the pages?
A:45
* GET/QueryString
* POST
Q:46 What is the difference between ereg_replace() and eregi_replace()?
A:46 eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
Q:47 What are the different functions in sorting an array?
A:47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().
Q:48 How can we know the count/number of elements of an array?
A:48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
Q:49 What is the PHP predefined variable that tells the What types of
images that PHP supports?
A:49 Though i am not sure if this is wrong or not, With the exif extension you are able to work with image meta data.
Q:50 How can I know that a variable is a number or not using a JavaScript?
A:50 bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.
Q:51 List out some tools through which we can draw E-R diagrams for
mysql.
A:51 Case Studio
Smart Draw
Q:52 How can I retrieve values from one database server and store them
in other database server using PHP?
A:52 we can always fetch from one database and rewrite to another. here
is a nice solution of it.$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);At this point you can only fetch records from you previous ResultSet,
i.e $res1 – But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script will fail
$res3 = mysql_query(”query”,$db1); //this will failSo how to solve that?
take a look below.
$db1 = mysql_connect(”host”,”user”,”pwd”)
mysql_select_db(”db1″, $db1);
$res1 = mysql_query(”query”,$db1);
$db2 = mysql_connect(”host”,”user”,”pwd”, true)
mysql_select_db(”db2″, $db2);
$res2 = mysql_query(”query”,$db2);
So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.
now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);
Thanks goes to Hasan and Hasin for this solution.
Q:53 List out the predefined classes in PHP?
A:53 Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
Q:54 How can I make a script that can be bi-language (supports
English, German)?
A:54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.
Q:55 What are the difference between abstract class and interface?
A:55 Abstract class: abstract classes are the class where one or more
methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not
define. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods are
abstract. That means all the methods only declared but not defined. All
the methods must be define by its implemented class.
Q:56 How can we send mail using JavaScript?
A:56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.
Q:57 How can we repair a MySQL table?
A:57 The syntex for repairing a MySQL table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified if the quick is given the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row
Q:58 What are the advantages of stored procedures, triggers, indexes?
A:58 A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.
Q:59 What is the maximum length of a table name, database name, and
fieldname in MySQL?
A:59 The following table describes the maximum length for each type of identifier.
Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255
There are some restrictions on the characters that may appear in identifiers:
Q:60 How many values can the SET function of MySQL take?
A:60 MySQL set can take zero or more values but at the maximum it can
take 64 values
Q:61 What are the other commands to know the structure of table using
MySQL commands except explain command?
A:61 describe Table-Name;
Q:62 How many tables will create when we create table, what are they?
A:62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Q:63 What is the purpose of the following files having extensions 1) .frm
2) .myd 3) .myi? What do these files contain?
A:63 In MySql, the default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
Q:64 What is maximum size of a database in MySQL?
A:64 If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database
performance can be adversely affected. The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation
specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB

Q:65 Give the syntax of Grant and Revoke commands?
A:65 The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password] now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname and username@%
where hostname is any valid hostname and % represents any name, the *.* any condition password is simply the password of userThe generic syntax for revoke is as following  > REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc. username@hotsname can be either username@localhost, username@hostname
and username@% where hostname is any valid hostname and % represents any name, the *.* any condition
Q:66 Explain Normalization concept?
A:66 The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table
Q:67 How can we find the number of rows in a table using MySQL?
A:67 Use this for mysql
>SELECT COUNT(*) FROM table_name;
Q:68 How can we find the number of rows in a result set using PHP?
A:68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
Q:69 How many ways we can we find the current date using MySQL?
A:69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()
Q:70 What are the advantages and disadvantages of Cascading Style Sheets?
A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once.Classes can be created for use on multiple HTML element types in many documents. Selector and grouping methods can be used to apply styles under complex contextsDisadvantagesAn extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions
Embedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document. Selector and grouping methods can be used to apply styles under complex contexts. No additional downloads necessary to receive style information
Disadvantages
This method can not control styles for multiple documents at once Inline Styles
Advantages
Useful for small quantities of style definitions. Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods
Disadvantages
Does not distance style information from content (a main goal of SGML/HTML). Can not control styles for multiple documents at once. Author can not create or control classes of elements to control multiple element types within the document. Selector grouping methods can not be used to create complex element addressing scenarios
Q:71 What type of inheritance that PHP supports?
A:71 In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.
Q:72 What is the difference between Primary Key and Unique key?
A:72 Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table.
Q:73 The structure of table view buyers is as follows:
Field Type Null Key Default Extra user_pri_id int(15) PRI null auto_increment userid varchar(10) YES null the value of user_pri_id the last row 999 then What will happen in the following conditions?

Condition1: Delete all the rows and insert another row then. What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and insert another row then. What is the value for this auto incremented field user_pri_id
A:73 In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000

Q:74 What are the advantages/disadvantages of MySQL and PHP?
A:74 Both of them are open source software (so free of cost), support cross platform. php is faster then ASP and JSP.

Q:75 What is the difference between GROUP BY and ORDER BY in Sql?
A:75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average

Q:76 What is the difference between char and varchar data types?
A:76 Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char takes a byte. rest 10 bytes will be free.

Q:77 What is the functionality of md5 function in PHP?
A:77 Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using.

Q:78 How can I load data from a text file into a table?
A:78 you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly

Q:79 How can we know the number of days between two given dates using
MySQL?

A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);

How can we know the number of days between two given dates using
PHP?

A:80 $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15′;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

PHP Interview Questions and Answers

1. What does a special set of tags do in PHP?
The output is displayed directly to the browser.

2. What’s the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?
In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.

5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);

6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b

7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

8. 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.

9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

10. How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.

11. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? - 100, it’s a reference to existing variable.

12. What’s the difference between accessing a class method via -> and via ::? - :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

13. Are objects passed by value or by reference? - Everything is passed by value.

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

15. What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

16. Why doesn’t the following code print the newline properly?
Because inside the single quotes the n character is not interpreted as newline, just as a sequence of two characters - and n.

17. Would you initialize your strings with single quotes or double quotes? - Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

18. How come the code works, but doesn’t for two-dimensional array of mine? - Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked.

19. What is the difference between characters �23 and x23? - The first one is octal 23, the second is hex 23.

20. With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.

Tuesday, June 30, 2009

Using GET and POST method in XMLHTTPRequest(Ajax) PHP Java Jsp

Requirements
Create a XMLHTTPRequest Object that uses the POST method.var http = new XMLHttpRequest();

Using GET method
Now we open a connection using the GET method.var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET“, url+”?”+params, true);
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(null);

I really hope that this much is clear for you
POST method
We are going to make some modifications so POST method will be used when sending the request…

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST“, url, true);
//Send the proper header information along with the request
http.setRequestHeader(”Content-type”, “application/x-www-form-urlencoded”);
http.setRequestHeader(”Content-length”, params.length);
http.setRequestHeader(”Connection”, “close”);
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(params);
The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument – in the GET method, we send the parameters along with the url separated by a ‘?’ character…http.open("GET",url+”?”+params, true);

But in the POST method we will use just the url as the second argument. We will send the parameters later.http.open("POST", url, true);

Some http headers must be set along with any POST request. So we set them in these lines…http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}

We set a handler for the ‘ready state’ change event. This is the same handler we used for the GET method. You can use the http.responseText here – insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.
http.send(params);

Saturday, June 27, 2009

Syntax in jsp

Legend All tags are case sensitive.
A pair of single quotes is equivalent to a pair of double quotes.
Spaces are not allowed between an equals sign and an attribute value.

plain text = required bold = default italics = user-defined | = or
[ ] = optional { } = required choice ... = list of items + = can repeat
HTML Comment Creates a comment that is sent to the client in the viewable page source.

Hidden Comment Documents the JSP file, but is not sent to the client.
<%-- comment --%>

Declaration Declares variables or methods valid in the page scripting language.
<%! declaration; [ declaration; ]+ ... %>

Expression Contains an expression valid in the page scripting language.
<%= expression %>

Scriptlet Contains a code fragment valid in the page scripting language.
<% code fragment of one or more lines %>

Include Directive Includes a static file, parsing the file’s
JSP elements.
<%@ include file="relativeURL" %>

Page Directive Defines attributes that apply to an entire JSP page.
<%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*} , ... " ] [ session="true|false" ] [ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ] [ isThreadSafe="true|false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="{mimeType [ ; charset=characterSet ] | text/html ; charset=ISO-8859-1}" ] [ isErrorPage="true|false" ] %>

Taglib Directive Defines a tag library and prefix for the custom tags used in the JSP page.
<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>

Accesses a custom tag’s functionality. other tags and data
Forwards a client request to an HTML
file, JSP file, or servlet for processing.
}"
{ /> |
> [ }" /> ]+
}

Gets the value of a bean property so that
you can display it in a result page.


Includes a static file or sends a request to a dynamic file.
}" flush="true"
{ /> |
> [ }" /> ]+
}

Downloads plug-in software to the Web
browser to execute an applet or bean.
[ name="instanceName" ] [ archive="URIToArchive, ..." ] [ align="bottom|top|middle|left|right" ]
[ height="displayPixels" ] [ width="displayPixels" ] [ hspace="leftRightPixels" ] [ vspace="topBottomPixels" ]
[ jreversion="JREVersionNumber | 1.1" ] [ nspluginurl="URLToPlugin" ] [ iepluginurl="URLToPlugin" ] >
[ [ }" /> ]+
]
[ text message for user ]

Sets a property value or values in a
bean.
{ property="*" | property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{string | <%= expression %>}" } />
Locates or instantiates a bean with a
specific name and scope.
{ class="package.class" [ type="package.class" ] | type="package.class" |
beanName="{package.class | <%= expression %>}" type="package.class" }
{ /> | > other elements
}

Implicit Objects Type Scope Some Useful Methods (see class or interface for others)
request Subclass of javax.servlet.ServletRequest Request getAttribute, getParameter, getParameterNames, getParameterValues, setAttribute
response Subclass of javax.servlet.ServletResponse Page Not typically used by JSP page authors
pageContext javax.servlet.jsp.PageContext Page findAttribute, getAttribute, getAttributesScope, getAttributeNamesInScope, setAttribute

session javax.servlet.http.HttpSession Session getAttribute, getId, setAttribute
application javax.servlet.ServletContext Application getAttribute, getMimeType, getRealPath, setAttribute

out javax.servlet.jsp.JspWriter Page clear, clearBuffer, flush, getBufferSize, getRemaining
config javax.servlet.ServletConfig Page getInitParameter, getInitParameterNames
page java.lang.Object Page Not typically used by JSP page authors
exception java.lang.Throwable Page getMessage, getLocalizedMessage, printStackTrace, toString

Thursday, June 11, 2009

Operator and Function Reference in mysql

 Operator and Function Reference

Name Description
ABS() Return the absolute value
ACOS() Return the arc cosine
ADDDATE()(v4.1.1) Add dates
ADDTIME()(v4.1.1) Add time
AES_DECRYPT() Decrypt using AES
AES_ENCRYPT() Encrypt using AES
AND, && Logical AND
ASCII() Return numeric value of left-most character
ASIN() Return the arc sine
ATAN2(), ATAN() Return the arc tangent of the two arguments
ATAN() Return the arc tangent
AVG() Return the average value of the argument
BENCHMARK() Repeatedly execute an expression
BETWEEN ... AND ... Check whether a value is within a range of values
BIN() Return a string representation of the argument
BINARY Cast a string to a binary string
BIT_AND() Return bitwise and
BIT_COUNT() Return the number of bits that are set
BIT_LENGTH() Return length of argument in bits
BIT_OR() Return bitwise or
BIT_XOR()(v4.1.1) Return bitwise xor
& Bitwise AND
~ Invert bits
| Bitwise OR
^ Bitwise XOR
CASE Case operator
CAST() Cast a value as a certain type
CEIL() Return the smallest integer value not less than the argument
CEILING() Return the smallest integer value not less than the argument
CHAR_LENGTH() Return number of characters in argument
CHAR() Return the character for each integer passed
CHARACTER_LENGTH() A synonym for CHAR_LENGTH()
CHARSET()(v4.1.0) Return the character set of the argument
COALESCE() Return the first non-NULL argument
COERCIBILITY()(v4.1.1) Return the collation coercibility value of the string argument
COLLATION()(v4.1.0) Return the collation of the string argument
COMPRESS()(v4.1.1) Return result as a binary string
CONCAT_WS() Return concatenate with separator
CONCAT() Return concatenated string
CONNECTION_ID() Return the connection ID (thread ID) for the connection
CONV() Convert numbers between different number bases
CONVERT_TZ()(v4.1.3) Convert from one timezone to another
Convert() Cast a value as a certain type
COS() Return the cosine
COT() Return the cotangent
COUNT(DISTINCT) Return the count of a number of different values
COUNT() Return a count of the number of rows returned
CRC32()(v4.1.0) Compute a cyclic redundancy check value
CURDATE() Return the current date
CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP Synonyms for NOW()
CURRENT_USER(), CURRENT_USER Return the username and hostname combination
CURTIME() Return the current time
DATABASE() Return the default (current) database name
DATE_ADD() Add two dates
DATE_FORMAT() Format date as specified
DATE_SUB() Subtract two dates
DATE()(v4.1.1) Extract the date part of a date or datetime expression
DATEDIFF()(v4.1.1) Subtract two dates
DAY()(v4.1.1) Synonym for DAYOFMONTH()
DAYNAME()(v4.1.21) Return the name of the weekday
DAYOFMONTH() Return the day of the month (0-31)
DAYOFWEEK() Return the weekday index of the argument
DAYOFYEAR() Return the day of the year (1-366)
DECODE() Decodes a string encrypted using ENCODE()
DEFAULT() Return the default value for a table column
DEGREES() Convert radians to degrees
DES_DECRYPT() Decrypt a string
DES_ENCRYPT() Encrypt a string
DIV(v4.1.0) Integer division
/ Division operator
ELT() Return string at index number
ENCODE() Encode a string
ENCRYPT() Encrypt a string
<=> NULL-safe equal to operator
= Equal operator
EXP() Raise to the power of
EXPORT_SET() Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string
EXTRACT Extract part of a date
ExtractValue()(v5.1.5) Extracts a value from an XML string using XPath notation
FIELD() Return the index (position) of the first argument in the subsequent arguments
FIND_IN_SET() Return the index position of the first argument within the second argument
FLOOR() Return the largest integer value not greater than the argument
FORMAT() Return a number formatted to specified number of decimal places
FOUND_ROWS() For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIME() Format UNIX timestamp as a date
GET_FORMAT()(v4.1.1) Return a date format string
GET_LOCK() Get a named lock
>= Greater than or equal operator
> Greater than operator
GREATEST() Return the largest argument
GROUP_CONCAT()(v4.1) Return a concatenated string
HEX() Return a hexadecimal representation of a decimal or string value
HOUR() Extract the hour
IF() If/else construct
IFNULL() Null if/else construct
IN() Check whether a value is within a set of values
INET_ATON() Return the numeric value of an IP address
INET_NTOA() Return the IP address from a numeric value
INSERT() Insert a substring at the specified position up to the specified number of characters
INSTR() Return the index of the first occurrence of substring
INTERVAL() Return the index of the argument that is less than the first argument
IS_FREE_LOCK() Checks whether the named lock is free
IS NOT NULL NOT NULL value test
IS NOT Test a value against a boolean
IS NULL NULL value test
IS_USED_LOCK()(v4.1.0) Checks whether the named lock is in use. Return connection identifier if true.
IS Test a value against a boolean
ISNULL() Test whether the argument is NULL
LAST_DAY(v4.1.1) Return the last day of the month for the argument
LAST_INSERT_ID() Value of the AUTOINCREMENT column for the last INSERT
LCASE() Synonym for LOWER()
LEAST() Return the smallest argument
<< Left shift
LEFT() Return the leftmost number of characters as specified
LENGTH() Return the length of a string in bytes
<= Less than or equal operator
< Less than operator
LIKE Simple pattern matching
LN() Return the natural logarithm of the argument
LOAD_FILE() Load the named file
LOCALTIME(), LOCALTIME Synonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()(v4.0.6) Synonym for NOW()
LOCATE() Return the position of the first occurrence of substring
LOG10() Return the base-10 logarithm of the argument
LOG2() Return the base-2 logarithm of the argument
LOG() Return the natural logarithm of the first argument
LOWER() Return the argument in lowercase
LPAD() Return the string argument, left-padded with the specified string
LTRIM() Remove leading spaces
MAKE_SET() Return a set of comma-separated strings that have the corresponding bit in bits set
MAKEDATE()(v4.1.1) Create a date from the year and day of year
MAKETIME(v4.1.1) MAKETIME()
MASTER_POS_WAIT() Block until the slave has read and applied all updates up to the specified position
MATCH Perform full-text search
MAX() Return the maximum value
MD5() Calculate MD5 checksum
MICROSECOND()(v4.1.1) Return the microseconds from argument
MID() Return a substring starting from the specified position
MIN() Return the minimum value
- Minus operator
MINUTE() Return the minute from the argument
MOD() Return the remainder
% Modulo operator
MONTH() Return the month from the date passed
MONTHNAME()(v4.1.21) Return the name of the month
NAME_CONST()(v5.0.12) Causes the column to have the given name
NOT BETWEEN ... AND ... Check whether a value is not within a range of values
!=, <> Not equal operator
NOT IN() Check whether a value is not within a set of values
NOT LIKE Negation of simple pattern matching
NOT REGEXP Negation of REGEXP
NOT, ! Negates value
NOW() Return the current date and time
NULLIF() Return NULL if expr1 = expr2
OCT() Return an octal representation of a decimal number
OCTET_LENGTH() A synonym for LENGTH()
OLD_PASSWORD()(v4.1) Return the value of the old (pre-4.1) implementation of PASSWORD
||, OR Logical OR
ORD() Return character code for leftmost character of the argument
PASSWORD() Calculate and return a password string
PERIOD_ADD() Add a period to a year-month
PERIOD_DIFF() Return the number of months between periods
PI() Return the value of pi
+ Addition operator
POSITION() A synonym for LOCATE()
POW() Return the argument raised to the specified power
POWER() Return the argument raised to the specified power
PROCEDURE ANALYSE() Analyze the results of a query
QUARTER() Return the quarter from a date argument
QUOTE() Escape the argument for use in an SQL statement
RADIANS() Return argument converted to radians
RAND() Return a random floating-point value
REGEXP Pattern matching using regular expressions
RELEASE_LOCK() Releases the named lock
REPEAT() Repeat a string the specified number of times
REPLACE() Replace occurrences of a specified string
REVERSE() Reverse the characters in a string
>> Right shift
RIGHT() Return the specified rightmost number of characters
RLIKE Synonym for REGEXP
ROUND() Round the argument
ROW_COUNT()(v5.0.1) The number of rows updated
RPAD() Append string the specified number of times
RTRIM() Remove trailing spaces
SCHEMA()(v5.0.2) A synonym for DATABASE()
SEC_TO_TIME() Converts seconds to 'HH:MM:SS' format
SECOND() Return the second (0-59)
SESSION_USER() Synonym for USER()
SHA1(), SHA() Calculate an SHA-1 160-bit checksum
SIGN() Return the sign of the argument
SIN() Return the sine of the argument
SLEEP()(v5.0.12) Sleep for a number of seconds
SOUNDEX() Return a soundex string
SOUNDS LIKE(v4.1.0) Compare sounds
SPACE() Return a string of the specified number of spaces
SQRT() Return the square root of the argument
STD() Return the population standard deviation
STDDEV_POP()(v5.0.3) Return the population standard deviation
STDDEV_SAMP()(v5.0.3) Return the sample standard deviation
STDDEV() Return the population standard deviation
STR_TO_DATE()(v4.1.1) Convert a string to a date
STRCMP() Compare two strings
SUBDATE() A synonym for DATE_SUB() when invoked with three arguments
SUBSTR() Return the substring as specified
SUBSTRING_INDEX() Return a substring from a string before the specified number of occurrences of the delimiter
SUBSTRING() Return the substring as specified
SUBTIME()(v4.1.1) Subtract times
SUM() Return the sum
SYSDATE() Return the time at which the function executes
SYSTEM_USER() Synonym for USER()
TAN() Return the tangent of the argument
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIME()(v4.1.1) Extract the time portion of the expression passed
TIMEDIFF()(v4.1.1) Subtract time
* Times operator
TIMESTAMP()(v4.1.1) With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments
TIMESTAMPADD()(v5.0.0) Add an interval to a datetime expression
TIMESTAMPDIFF()(v5.0.0) Subtract an interval from a datetime expression
TO_DAYS() Return the date argument converted to days
TRIM() Remove leading and trailing spaces
TRUNCATE() Truncate to specified number of decimal places
UCASE() Synonym for UPPER()
- Change the sign of the argument
UNCOMPRESS()(v4.1.1) Uncompress a string compressed
UNCOMPRESSED_LENGTH()(v4.1.1) Return the length of a string before compression
UNHEX()(v4.1.2) Convert each pair of hexadecimal digits to a character
UNIX_TIMESTAMP() Return a UNIX timestamp
UpdateXML()(v5.1.5) Return replaced XML fragment
UPPER() Convert to uppercase
USER() Return the current username and hostname
UTC_DATE()(v4.1.1) Return the current UTC date
UTC_TIME()(v4.1.1) Return the current UTC time
UTC_TIMESTAMP()(v4.1.1) Return the current UTC date and time
UUID_SHORT()(v5.1.20) Return an integer-valued universal identifier
UUID()(v4.1.2) Return a Universal Unique Identifier (UUID)
VALUES()(v4.1.1) Defines the values to be used during an INSERT
VAR_POP()(v5.0.3) Return the population standard variance
VAR_SAMP()(v5.0.3) Return the sample variance
VARIANCE()(v4.1) Return the population standard variance
VERSION() Returns a string that indicates the MySQL server version
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR()(v4.1.1) Return the calendar week of the date (0-53)
XOR Logical XOR
YEAR() Return the year
YEARWEEK() Return the year and week

Thursday, May 21, 2009

XMLHttp POST Requests in php ajax

Now that you've seen how XMLHttp can simplify GET requests, it's time to take a look at POST requests. First, you need to make the same changes to SaveCustomer.php as you did for GetCustomerInfo.php, which means you need to remove extraneous HTML and JavaScript, add the content type information, and output the text:

This now represents the entirety of SaveCustomer.php. Note that the header() function is called to set the content type, and echo is used to output $sStatus. In the main page, the simple form that was set up to allow entry of new customer info is the following:

Enter customer information to be saved:

Customer Name:
Address:
City:
State:
Zip Code:
Phone:
E-mail:

You'll note that the onsubmit event handler has now changed to call the function sendRequest() (although the event handler still returns false to prevent actual form submission). This method first assembles the data for the POST request and then creates the XMLHttp object to send it. The data must be sent in the format as a query string:
name1=value1&name2=value2&name3=value3
Both the name and value of each parameter must be URL-encoded in order to avoid data loss during transmission. JavaScript provides a built-in function called encodeURIComponent() that can be used to perform this encoding. To create this string, you'll need to iterate over the form fields, extracting and encoding the name and value. The getRequestBody() function handles this:
function getRequestBody(oForm) { var aParams = new Array(); for (var i=0 ; i < sparam =" encodeURIComponent(oForm.elements[i].name);">
This function assumes that you will supply a reference to the form as an argument. An array (aParams) is created to store each individual name-value pair. Then, the elements of the form are iterated over, building up a string and storing it in sParam, which is then added to the array. Doing this prevents multiple string concatenation, which can lead to slower code execution in some browsers. The last step is to call join() on the array, passing in the ampersand character. This effectively combines all the name-value pairs with ampersands, creating a single string in the correct format.
The sendRequest() function calls getRequestBody() and sets up the request:
function sendRequest() { var oForm = document.forms[0]; var sBody = getRequestBody(oForm); var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("post", oForm.action, true); oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == 4) { if (oXmlHttp.status == 200) { saveResult(oXmlHttp.responseText); } else { saveResult("An error occurred: "+ oXmlHttp.statusText); } } }; oXmlHttp.send(sBody); }
As with previous examples, the first step in this function is to get a reference to the form and store it in a variable (oForm). Then, the request body is generated and stored in sBody. Next comes the creation and setup of the XMLHttp object. Note that the first argument of open() is now post instead of get, and the second is set to oForm.action (once again, so this script can be used on multiple pages). You'll also notice that a request header is being set. When a form is posted from the browser to a server, it sets the content type of the request as application/x-www-form-urlencoded. Most server-side languages look for this encoding in order to parse the incoming POST data properly, so it is very important for it to be set. The onreadystatechange event handler is very similar to that of the GET example; the only change is the call to saveResult() instead of displayCustomerInfo(). The last line is very important, as the sBody string is passed to send() so that it will become part of the request body. This effectively mimics what the browser does, so all server-side logic should work as expected.

Creating an XMLHttp Object in PHP AJAX

The first step to using an XMLHttp object is, obviously, to create one. Because Microsoft's implementation is an ActiveX control, you must use the proprietary ActiveXObject class in JavaScript, passing in the XMLHttp control's signature:
var oXmlHttp = new ActiveXObject("Microsoft.XMLHttp");
This line creates the first version of the XMLHttp object (the one shipped with IE 5.0). The problem is that there have been several new versions released with each subsequent release of the MSXML library. Each release brings with it better stability and speed, so you want to make sure you are always using the most recent version available on the user's machine. The signatures are:
1 Microsoft.XMLHttp 2 MSXML2.XMLHttp 3 MSXML2.XMLHttp.3.0 4 MSXML2.XMLHttp.4.0 5 MSXML2.XMLHttp.5.0
Unfortunately, the only way to determine the best version to use is to try to create each one. Because this is an ActiveX control, any failure to create an object will throw an error, which means that you must enclose each attempt within a try...catch block. The end result is a function such as this:
function createXMLHttp() { var aVersions = [ "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp" ]; for (var i = 0; i < oxmlhttp =" new">
The createXMLHttp() function stores an array of XMLHttp signatures, with the most recent one first. It iterates through this array and tries to create an XMLHttp object with each signature. If the creation fails, the catch statement prevents a JavaScript error from stopping execution; then the next signature is attempted. When an object is created, it is returned. If the function completes without creating an XMLHttp object, an error is thrown indicating that the creation failed. Fortunately, creating an XMLHttp object is much easier in other browsers. Mozilla Firefox, Safari, and Opera all use the same code:
var oXmlHttp = new XMLHttpRequest();
Naturally, it helps to have a cross-browser way of creating XMLHttp objects. You can create such a function by altering the createXMLHttp() function defined previously: function createXMLHttp() { if (typeof XMLHttpRequest != "undefined") { return new XMLHttpRequest(); } else if (window.ActiveXObject) { var aVersions = [ "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp" ]; for (var i = 0; i < oxmlhttp =" new">
The other option for creating cross-browser XMLHttp objects is to use a library that already has cross-browser code written. The zXml library, written by two of your authors, is one such library and is available for download at www.nczonline.net/downloads/. This library defines a single function for the creation of XMLHttp objects: var oXmlHttp = zXmlHttp.createRequest(); The createRequest() function, and the zXml library itself, will be used throughout this book to aid in cross-browser handling of Ajax technologies. Using XMLHttp After you have created an XMLHttp object, you are ready to start making HTTP requests from JavaScript. The first step is to call the open() method, which initializes the object. This method accepts the following three arguments:
Request Type: A string indicating the request type to be made — typically, GET or POST (these are the only ones currently supported by all browsers). URL: A string indicating the URL to send the request to. Async: A Boolean value indicating whether the request should be made asynchronously.
The last argument, async, is very important because it controls how JavaScript executes the request. When set to true, the request is sent asynchronously, and JavaScript code execution continues without waiting for the response; you must use an event handler to watch for the response to the request. If async is set to false, the request is sent synchronously, and JavaScript waits for a response from the server before continuing code execution. That means if the response takes a long time, the user cannot interact with the browser until the response has completed. For this reason, best practices around the development of Ajax applications favor the use of asynchronous requests for routine data retrieval, with synchronous requests reserved for short messages sent to and from the server. To make an asynchronous GET request to info.txt, you would start by doing this:
var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("get", "info.txt", true);
Note that the case of the first argument, the request type, is irrelevant even though technically request types are defined as all uppercase. Next, you need to define an onreadystatechange event handler. The XMLHttp object has a property called readyState that changes as the request goes through and the response is received. There are five possible values for readyState:
0 (Uninitialized): The object has been created but the open() method hasn't been called. 1 (Loading): The open() method has been called but the request hasn't been sent. 2 (Loaded): The request has been sent. 3 (Interactive). A partial response has been received. 4 (Complete): All data has been received and the connection has been closed.
Every time the readyState property changes from one value to another, the readystatechange event fires and the onreadystatechange event handler is called. Because of differences in browser implementations, the only reliable readyState values for cross-browser development are 0, 1, and 4. In most cases, however, you will check only for 4 to see when the request has returned: var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("get", "info.txt", true); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == 4) { alert("Got response."); } }; The last step is to call the send() method, which actually sends the request. This method accepts a single argument, which is a string for the request body. If the request doesn't require a body (remember, a GET request doesn't), you must pass in null:
var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("get", "info.txt", true); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == 4) { alert("Got response."); } }; oXmlHttp.send(null); That's it! The request has been sent and when the response is received, an alert will be displayed. But just showing a message that the request has been received isn't very useful. The true power of XMLHttp is that you have access to the returned data, the response status, and the response headers.
To retrieve the data returned from the request, you can use the responseText or responseXML properties. The responseText property returns a string containing the response body, whereas the responseXML property is an XML document object used only if the data returned has a content type of text/xml. (XML documents are discussed in Chapter 4.) So, to get the text contained in info.txt, the call would be as follows:
var sData = oXmlHttp.responseText;
Note that this will return the text in info.txt only if the file was found and no errors occurred. If, for example, info.txt didn't exist, then the responseText would contain the server's 404 message. Fortunately, there is a way to determine if any errors occurred. The status property contains the HTTP status code sent in the response, and statusText contains the text description of the status (such as "OK" or "Not Found"). Using these two properties, you can make sure the data you've received is actually the data you want or tell the user why the data wasn't retrieved: if (oXmlHttp.status == 200) { alert("Data returned is: "+ oXmlHttp.responseText; } else { alert("An error occurred: "+ oXmlHttp.statusText; } Generally, you should always ensure that the status of a response is 200, indicating that the request was completely successful. The readyState property is set to 4 even if a server error occurred, so just checking that is not enough. In this example, the responseText property is shown only if the status is 200; otherwise, the error message is displayed. Important The statusText property isn't implemented in Opera and sometimes returns an inaccurate description in other browsers. You should never rely on statusText alone to determine if an error occurred. As mentioned previously, it's also possible to access the response headers. You can retrieve a specific header value using the getResponseHeader() method and passing in the name of the header that you want to retrieve. One of the most useful response headers is Content-Type, which tells you the type of data being sent:
var sContentType = oXmlHttp.getResponseHeader("Content-Type"); if (sContentType == "text/xml") { alert("XML content received."); } else if (sContentType == "text/plain") { alert("Plain text content received."); } else { alert("Unexpected content received."); } This code snippet checks the content type of the response and displays an alert indicating the type of data returned. Typically, you will receive only XML data (content type of text/xml) or plain text (content type of text/plain) from the server, because these content types are the easiest to work with using JavaScript. If you'd prefer to see all headers returned from the server, you can use the getAllResponseHeaders() method, which simply returns a string containing all of the headers. Each heading in the string is separated by either a new line character (\n in JavaScript) or a combination of the carriage return and new line (\r\n in JavaScript), so you can deal with individual headers as follows:
var sHeaders = oXmlHttp.getAllResponseHeaders(); var aHeaders = sHeaders.split(/\r?\n/); for (var i=0; i <>
It's also possible to set headers on the request before it's sent out. You may want to indicate the content type of data that you'll be sending, or you may just want to send along some extra data that the server may need to deal with the request. To do so, use the setRequestHeader() method before calling send():
var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("get", "info.txt", true); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == 4) { alert("Got response."); } }; oXmlHttp.setRequestHeader("myheader", "myvalue"); oXmlHttp.send(null); In this code, a header named myheader is added to the request before it's sent out. The header will be added to the default headers as myheader: myvalue. Up to this point, you've been dealing with asynchronous requests, which are preferable in most situations. Sending synchronous requests means that you don't need to assign theonreadystatechange event handler because the response will have been received by the time the send() method returns. This makes it possible to do something like this: var oXmlHttp = zXmlHttp.createRequest(); oXmlHttp.open("get", "info.txt", false); oXmlHttp.send(null); if (oXmlHttp.status == 200) { alert("Data returned is: "+ oXmlHttp.responseText; } else { alert("An error occurred: "+ oXmlHttp.statusText; }
Sending the request synchronously (setting the third argument of open() to false) enables you to start evaluating the response immediately after the call to send(). This can be useful if you want the user interaction to wait for a response or if you're expecting to receive only a very small amount of data (for example, less than 1K). In the case of average or larger amounts of data, it's best to use an asynchronous call.