Search

Monday, August 25, 2008

PHP Queries

Question : 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?

Answer : 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.

Question : Who is the father of PHP and explain the changes in PHP versions?

Answer : 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 additional OOPs features.

Question : How can we submit a form without a submit button?

Answer : 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).

Question : 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

Question : What is the difference between mysql_fetch_object and
mysql_fetch_array?

Answer : mysql_fetch_object() is similar to mysql_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).

Question : What is the difference between $message and $$message?

Answer : It is a classic example of PHP’s variable variables. take the following example.

$message = “Shashi”;

$$message = “is a owner of http://www.shashionline.in/ “;

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

Question : How can we extract string ‘shashionline.in ‘ from a string info@shashionline.in using regular expression of PHP?

Answer : preg_match(”/^http://.+@(.+)$/”,’info@shashionline.in’,$found);
echo $found[1];

Question : 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”).

Question : What are the differences between require and include, include_once and require_once?

Answer :

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.

Question : Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?

Answer : Yes we can use include() more than one time in any page though it is not a very good practice.

Question : 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)) ?

Answer : Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.

Question : Functions in IMAP, POP3 AND LDAP?

Answer : You can find these specific information in PHP Manual.

Question : How can I execute a PHP script using command line?

Answer : 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.

Question : Suppose your Zend engine supports the mode . Then how can you
configure your PHP Zend engine to support mode ?

Answer : In php.ini file:
set
short_open_tag=on
to make PHP support

Question : Shopping cart online validation i.e. how can we configure Paypal,
etc.?

Answer : We can find the detail documentation about different paypal integration process at the following site PayPal PHP
SDK : http://www.paypaldev.org/

Question : What is meant by nl2br()?

Answer : Inserts HTML line breaks
(
)
before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines.
For example: echo nl2br(”god blessn you”) will output “god bless
you” to your browser.

Question : Draw the architecture of Zend engine?

Answer : 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:

Zend Engine

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.

Zend Engine

PHP Scripts are loaded into memory and compiled into Zend opcodes.

Question : What are the current versions of apache, PHP, and MySQL?

Answer : As of February, 2007 the current versions are PHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4
Note: visit
http://www.php.net/,
http://dev.mysql.com/downloads/mysql/,
http://www.apache.org/ to get current
versions.

Question : What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and operating systems?

Answer : 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.

Question : How can we encrypt and decrypt a data present in a MySQL table using MySQL?

Answer : AES_ENCRYPT () and AES_DECRYPT ()

Question : How can we encrypt the username and password using PHP?

Answer : 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()

Question : What are the features and advantages of object-oriented programming?

Answer : 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.

Question : What are the differences between procedure-oriented languages and
object-oriented languages?

Answer : 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.

Question : What is the use of friend function?

Answer : 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.

Question : What are the differences between public, private, protected,static, transient, final and volatile?

Answer : 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.

Question : What are the different types of errors in PHP?

Answer : 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.

Question : What is the functionality of the function strstr and stristr?

Answer : 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().

Question : What are the differences between PHP 3 and PHP 4 and PHP 5?

Answer : Please read the release notes at
http://php.net/

Question : How can we convert asp pages to PHP pages?

Answer : 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/

Question : What is the functionality of the function htmlentities?

Answer : 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.

Question : How can we get second of the current time using date function?

Answer : $second = date(”s”);

Question : How can we convert the time zones using PHP?

Answer : By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:
date_default_timezone_set(’Asia/Tokyo’);

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern
date_default_timezone_set(’US/Eastern’);

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘

‘, date(DATE_RFC1123, $stamp) ,’

‘; ?>

Question : What is meant by urlencode and urldecode?

Answer : 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.

Question : What is the difference between the functions unlink and unset?

Answer : unlink() deletes the given file from the file system.
unset() makes a variable undefined.

Question : How can we register the variables into a session?

Answer : $_SESSION[’name’] = “Shashi”;

Question : How can we get the properties (size, type, width, height) of an image using PHP image functions?

Answer : 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

Question : How can we get the browser properties using PHP?

Answer : By using
$_SERVER[’HTTP_USER_AGENT’] variable.

Question : What is the maximum size of a file that can be uploaded using PHP
and how can we change this?

Answer : By default the maximum size is 2MB. and we can change the following setup at php.iniupload_max_filesize = 2M

Question : How can we increase the execution time of a PHP script?

Answer : by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds

Question : How can we take a backup of a MySQL table and how can we restore it. ?

Answer : 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!

Question : How can we optimize or increase the speed of a MySQL select query?

Answer : • 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 arequerying.
•use limit keyword if you are looking for any specific number of rows from the result set.

Question : How many ways can we get the value of current session id?

Answer : How many ways can we get the value of current session id? session_id() returns the session id for the current session.

Question : How can we destroy the session, how can we unset the variable of a session?

Answer : session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables

Question : How can we destroy the cookie?

Answer : Set the cookie in past.

Question : How many ways we can pass the variable through the navigation between the pages?

Answer : •GET/QueryString
•POST

Question : What is the difference between ereg_replace() and eregi_replace()?

Answer : 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.

Question : What are the different functions in sorting an array?

Answer : Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().

Question : How can we know the count/number of elements of an array?

Answer : 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)

Question : What is the PHP predefined variable that tells the What types of
images that PHP supports?

Answer : Though i am not sure if this is wrong or not, With the exif extension you are able to work with image meta data.

Question : How can I know that a variable is a number or not using a JavaScript?

Answer : 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.

Question : List out some tools through which we can draw E-R diagrams formysql.

Answer :
Case Studio
Smart Draw

Question : How can I retrieve values from one database server and store themin other database server using PHP?

Answer : WeWe 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 yousupply 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 whichindicates whether a link will be created or not. As we connect to the $db2 with this optional parameter set to ‘true’, so both link willremain live. Now the following query will execute successfully.
$res3 = mysql_query(”query”,$db1);

Question : List out the predefined classes in PHP?

Answer : Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

Question : How can I make a script that can be bi-language (supportsEnglish, German)?

Answer : 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 run-time choose the required language option.

Question : What are the difference between abstract class and interface?

Answer : Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class but notdefine. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods areabstract. That means all the methods only declared but not defined. Allthe methods must be define by its implemented class.

Question : How can we send mail using JavaScript?

Answer : JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an email to send. this requires the clientto approve it.

Question : How can we repair a MySQL table?

Answer : 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 givenit will create index row by row.

Question : What are the advantages of stored procedures, triggers, indexes?

Answer : A stored procedure is a set of SQL commands that can be compiled andstored in the server. Once this has been done, clients don’t need tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level by havinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more ofthe 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 ofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer 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 readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.

Question : What is the maximum length of a table name, database name, andfieldname in MySQL?

Answer : The following table describes the maximum length for each type ofidentifier.

Identifier Maximum Length(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255

There are some restrictions on the characters that may appear inidentifiers.

Question : How many values can the SET function of MySQL take?

Answer : MySQL set can take zero or more values but at the maximum it cantake 64 values.

Question : What are the other commands to know the structure of table usingMySQL commands except explain command?

Answer : describe Table-Name;

Question : How many tables will create when we create table, what are they?

Answer : The ‘.frm’ file stores the table definition.The data file has a ‘.MYD’ (MYData) extension.The index file has a ‘.MYI’ (MYIndex) extension.

Question : What is the purpose of the following files having extensions 1) .frm2) .myd 3) .myi? What do these files contain?

Answer : In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files have namesthat begin with the table name and have an extension to indicate thefile type.The ‘.frm’ file stores the table definition.The data file has a ‘.MYD’ (MYData) extension.The index file has a ‘.MYI’ (MYIndex) extension.

Question : What is maximum size of a database in MySQL?

Answer : If the operating system or filesystem places a limit on the numberof files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers offiles in a directory can place a practical limit on the number of tablesin a database. If the time required to open a file in the directoryincreases significantly as the number of files increases, databaseperformance 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 MyISAMstorage engine in MySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed table size,the maximum effective table size for MySQL databases is usuallydetermined by operating system constraints on file sizes, not by MySQLinternal limits.The InnoDB storage engine maintains InnoDB tables within a tablespacethat can be created from several files. This allows a table to exceedthe maximum individual file size. The tablespace can include raw diskpartitions, which allows extremely large tables. The maximum tablespacesize is 64TB.The following table lists some examples of operating system file-sizelimits. 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 documentationspecific 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

Question : Give the syntax of Grant and Revoke commands?

Answer : 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 specificdatabase 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 user.
The 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

Question : Explain Normalization concept?

Answer : The normalization process involves getting our data to conform tothree progressive normal forms, and a higher level of normalizationcannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academic andwill not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant datafrom horizontal rows. We want to ensure that there is no duplication ofdata in a given row, and that every column stores the least amount ofinformation possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across ahorizontal row, Second Normal Form (or 2NF) deals with redundancy ofdata in vertical columns. As stated earlier, the normal forms areprogressive, so to achieve Second Normal Form, your tables must alreadybe in First Normal Form.Third Normal Form I have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is notfully dependant on the primary key, but dependant on another value inthe table.

Question : How can we find the number of rows in a table using MySQL?

Answer : Use this for mysql>SELECT COUNT(*) FROM table_name;

Question : How can we find the number of rows in a result set using PHP?

Answer :
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;

Question : How many ways we can we find the current date using MySQL?

Answer :
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use SELECT CURTIME();
CURRENT_TIME() = CURTIME()

Question : What are the advantages and disadvantages of Cascading StyleSheets?

Answer :
External Style Sheets
Advantages : Can control styles for multiple documents at once. Classes can becreated for use on multiple HTML element types in many documents.Selector and grouping methods can be used to apply styles under complex contexts.
Disadvantages : An extra download is required to import style information for eachdocument The rendering of the document may be delayed until the externalstyle sheet is loaded becomes slightly unwieldy for small quantities ofstyle 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 complexcontexts. 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 otherstyle specification methods at the local level so only exceptions needto be listed in conjunction with other style methods.
Disadvantages : Does not distance style information from content (a main goal ofSGML/HTML). Can not control styles for multiple documents at once.Author can not create or control classes of elements to control multipleelement types within the document. Selector grouping methods can not beused to create complex element addressing scenarios

Question : What type of inheritance that PHP supports?

Answer : In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not supported. Classes are extendedusing the keyword ‘extends’.

Question : What is the difference between Primary Key andUnique key?

Answer : Primary Key: A column in a table whose values uniquely identify therows in the table. A primary key value cannot be NULL. Unique Key: Unique Keys are used to uniquely identify each row in thetable. 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 morethan one unique for a table.

Question : 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 inthe 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) andinsert another row then. What is the value for this auto incremented field user_pri_id.

Answer : In both cases let the value for auto increment field be n then nextrow will have value n+1 i.e. 1000.

Question : What are the advantages/disadvantages of MySQL and PHP?

Answer : Both of them are open source software (so free of cost), supportcross platform. php is faster then ASP and JSP.

Question : What is the difference between GROUP BY and ORDER BY in Sql?

Answer : ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columnsit should sort the result. If two rows will hawe the same value in col1it will try to sort them according to col2 and so on.GROUP BY[col1],[col2],…,[coln]; Tels DBMS to group results with same value ofcolumn col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, ifyou want to count all items in group, sum all values or view average.

Question : What is the difference between char and varchar data types?

Answer : Set char to occupy n bytes and it will take n bytes even if u rstoring a value of n-m bytesSet varchar to occupy n bytes and it will take only the required spaceand will not use the n byteseg. name char(15) will waste 10 bytes if we store ‘mizan’, if each chartakes a byteeg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if eachchar takes a byte. rest 10 bytes will be free.

Question : What is the functionality of md5 function in PHP?

Answer : Calculate the md5 hash of a string. The hash is a 32-characterhexadecimal number. I use it to generate keys which I use to identifyusers etc. If I add random no techniques to it the md5 generated nowwill be totally different for the same string I am using.

Question : How can I load data from a text file into a table?

Answer : you can use LOAD DATA INFILE file_name; syntax to load datafrom a text file. but you have to make sure thata) data is delimitedb) columns and data matched correctly.

Question : How can we know the number of days between two given dates usingMySQL?

Answer : SELECT DATEDIFF(’2007-03-07?,’2005-01-01?);

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

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

PHP interview questions

Explain about the installation of PHP on UNIX systems?
PHP can be installed on UNIX in many different ways there are pre defined packages available which can ease the process. Initially it can be controlled by the command line options. Help can be obtained from./configure help command. After installing PHP modules or executables can be configures and make command should help you in the process.

How to enable parsing?
Parsing is an important concept if you want to run your code appropriately and timely. PHP parses all the code present between the opening and closing tags, it ignores everything present out of the closing and opening tags. This tags allow PHP to be embedded between many documents.

What are the different opening and closing tags available in PHP?
There are four different types of tags available in PHP they are
*
*

* PHP short tags
* ASP style tags.
Generally the first two tags are widely used because they are portable.

Explain about array uintersect()?
This function is very useful in PHP. This function compares array values in a user defined function and it returns the array. If assoc() is added to the function it compares array keys. This function can also be defined as array uintersect uassoc().

Explain about converting an object?
When an object is converted into an object the stance of the object is not modified. A new instance of the class is created if a value of different type if converted into an object. Incase the value is null at the time of conversion the new instance will be empty.

Explain about resource?
Resource holds reference to an external resource and it is a special variable. These are created and used by specially defined functions. Resource holds defined and special handlers for opening files. Converting to a resource makes no sense at all.

Explain about null?
Null represents a variable with no value inside. There doesn’t exist any value for type Null. Null is defined to be null if and only if it is assigned a constant null, there is no value set, it is set to be unset(). This is the case insensitive keyword. There are also two functions they are is_null and unset().

Explain about mixed and callback functions?
Mixed function indicates that the function may contain multiple types but it doesn’t form a necessary condition. Functions like call_user_func() or usort() accept user defined functions as parameter. These functions are not only simple but also object methods which includes static methods.

Explain about PHP looping?
Looping statements are used in PHP to execute the code for a developer defined number of times. PHP has these following looping statements they are while, do while, for and for each. Foreach is used to loop a block of code in each element in an array.

Explain about Booleans in PHP?
A Boolean type states a truth value whether it is true or false. These statements are case insensitive. An operator returns a Boolean value and this value is passed onto the control structure which executes the statement. If an argument is required it is automatically converted.

Explain about Type juggling?
PHP uses Type juggling similar to the way Perl uses. Variable is defined in the context in which it is used. It doesn’t require any explicit definition for a function to perform its duties. For example if a string value is assigned to a variable it is defined as string.

Explain about the casts allowed in PHP?
Type casting acts and functions similarly as it performs in C. The casts allowed are Integer, Boolean, float and double, string, binary, array and object. Casting and support was added in PHP 5.2.1. A variable can be enclosed in double quotes instead of casting it to a string.

How to change the principal password?
Principal password can be changed by using kadm5_chpass_principal command. If you also want to specify the new password for effecting a change to the principal password it should be as
Bool kadm5_chpass_principal (resource $handle, string $principal, string password). This changes the password to password.

Explain about the advantages of using PHP?
There are many advantages of PHP they are
1) Easy and fast creation of dynamic web pages and a developer can also embed these dynamic functions into HTML.
2) A huge community resource which has a ton of information before you.
3) Connectivity ability lets you to connect to different interfaces and predefined libraries.
4) Execution is very fast because it uses less system resources, etc.

Explain about the connective abilities of the PHP?
A huge advantage for PHP is its connective ability. It uses huge number of extensions to interface with huge pool of libraries such as XML, graphics and encryption. Programmers can create their own extensions and compiling them. They can load their own programs by using the dynamic loading mechanism.

How can MYSQL functions be available with PHP?
MYSQL is not available as a default feature it must be created by the user. You can use --with-mysql=DIR function to make available SQL on your system. Compiling PHP functions with MYSQL will increase the support and functioning of the language. MYSQL should be installed where there are extensions of PHP.

Sunday, June 8, 2008

Best PHP Based Interview Questions and answers

1.What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods?
-->
GET :
- GET method have not security because of data view in
addressbar. For ex: we can not use this method for checking
login
- We can bookmark link with this method
- Server can log all action
- because of server log, we can pass 255 char. as query
string

POST:
- POST method have security of data.
- We can not bookmark page link
- We can pass unlimited data by this method as query string

2. How can we submit a form without a submit button?
--> you can submit a form with javascript like this:
document.forms[0].submit();

3. In how many ways we can retrieve the data in the result set of mysql using PHP?
--> 4 ways
1. mysql_fetch_rows
2. mysql_fetch_object
3. mysql_fetch_assoc
4. mysql_fetch_array

4. What is the difference between mysql_fetch_object and mysql_fetch_array?
-->
mysql_fetch_object : will return the results from database
as objects. fields will be accessible like in objects
i.e $result->name,$result->cust_name

mysql_fetch_array : will return the results from database as
array. fields will be accessible like in objects
i.e $result[name],$result[cust_name]

5. What is the difference between $message and $$message?
-->
$Message = "YOU";
$you= "Me";

echo $message //Output:- you
echo $$message //output :-Me

It means
$message is a variable and
$$Message is variable of variable

A variable of variable allows us to change the name of
variable dinamically

6. What are the differences between require and include, include_once?
-->Difference between require() and require_once(): require() includes and
evaluates a specific file, while require_once() does that only if it
has not been included before (on the same page). So, require_once() is
recommended to use when you want to include a file where you have a lot
of functions for example. This way you make sure you don't include the
file more times and you will not get the "function re-declared" error.
Difference between require() and include() is that require() produces a
FATAL ERROR if the file you want to include is not found, while
include() only produces a WARNING. There is also include_once() which
is the same as include(), but the difference between them is the same
as the difference between require() and require_once().

7. What is CAPTCHA?
-->CAPTCHA stands for Completely Automated Public Turing Test to tell
Computers and Humans Apart. To prevent spammers from using bots to
automatically fill out forms, CAPTCHA programmers will generate an
image containing distorted images of a string of numbers and letters.
Computers cannot determine what the numbers and letters are from the
image but humans have great pattern recognition abilities and will be
able to fairly accurately determine the string of numbers and letters.
By entering the numbers and letters from the image in the validation
field, the application can be fairly assured that there is a human
client using it. To read more look here:
http://en.wikipedia.org/wiki/Captcha

8. If you have to work with dates in the following format: "Tuesday,
February 14, 2006 @ 10:39 am", how can you convert them to another
format, that is easier to use?
-->
The strtotime function can convert a string to a timestamp. A timestamp
can be converted to date format. So it is best to store the dates as
timestamp in the database, and just output them in the format you like.

So let's say we have
$date = "Tuesday, February 14, 2006 @ 10:39 am";
In
order to convert that to a timestamp, we need to get rid of the "@"
sign, and we can use the remaining string as a parameter for the
strtotime function.

So we have
$date = str_replace("@ ","",$date);
$date = strtotime($date);

now $date is a timestamp
and we can say:

echo date("d M Y",$date);

9. How we know browser properties?
-->get_browser() attempts to determine the capabilities of the user's
browser. This is done by looking up the browser's information in the
browscap.ini file.

echo $_SERVER['HTTP_USER_AGENT'] . "

\n";

$browser = get_browser();

foreach ($browser as $name => $value) {
echo "$name $value
\n";
}

10. How i will check that user is, logged in or not. i want to make it a function and i want to use in each page and after login i want to go in current page(same page. where i was working)?
-->For this we can use the session objec($_SESSION)t. When the user login with his/ her user name and password, usually we check those to ensure for correctness. If that user name and password are valid one then we can store that user name in a session and then we can very that session variable has been set or not in a single files and we can include that file in all pages.

11. How i can get ip address?
-->We can use SERVER var $_SERVER['SERVER_ADDR'] and getenv("REMOTE_ADDR") functions to get the IP address.

12. What is differenc between mysql_connect and mysql_pconnec?
-->mysql_pconnect establishes a persistent connection. If you don't need one (such as a website that is mostly HTML files or PHP files that don't call the db) then you don't need to use it. mysql_connect establishes a connection for the duration of the script that access the db. Once the script has finished executing it closes the connection. The only time you need to close the connection manually is if you jump out of the script for any reason.

If you do use mysql_pconnect. You only need to call it once for the session. That's the beauty of it. It will hold open a connection to the db that you can use over and over again simply by calling the resource ID whenever you need to interact with the db.

13. What is the difference between echo and print statement?
-->There is a slight difference between print and echo which would depend on how you want to use the outcome. Using the print method can return a true/false value. This may be helpful during a script execution of somesort. Echo does not return a value, but has been considered as a faster executed command. All this can get into a rather complicated discussion, so for now, you can just use whichever one you prefer.

14. How to make a download page in own site, which i can know that how many file has been loaded by particular user or particular ipaddress?
--> We can use hyperlink having URL where file are kept. and we only allow regisetered user to download. from session of user we can get the user detail

Tuesday, June 3, 2008

Php forum list

www.devnetwork.net/
www.phpfreaks.com/forums/
www.phpbb.com/
www.phpbuilder.com/board/
forums.digitalpoint.com/forumdisplay.php
www.zend.com/forums/
www.sitepoint.com/forums/forumdisplay.php
www.weberforums.com/
forums.mysql.com/read.php

Open Source Developers' Conference 2008 - Sydney - Call for Papers

The Open Source Developers' Conference 2008 is a conference run by open source developers, for developers and business people. It covers numerous programming languages across a range of operating systems, and related topics such as business processes, licensing, and strategy. Talks vary from introductory pieces through to the deeply technical. It is a great opportunity to meet, share, and learn with like-minded individuals.

This year, the conference will be held in Sydney, Australia during the first week of December. If you are an Open Source maintainer, developer or user, the organising committee would encourage you to submit a talk proposal on open source tools, solutions, languages or technologies you are working with.

For more details, see: http://osdc.com.au/2008/papers/cfp.html.

If you have any questions or require assistance with your submission, please don't hesitate to ask!

We continue to recognise the increasing importance of Open Source in providing a medium for collaboration between individuals, researchers, business and government. In recognition of this and ensure a high standard of presentations, we intend to peer-review all submitted papers.

OSDC 2008 Sydney (Australia) - Key Program Dates:

  1. 28 Apr - Call for Papers
  2. 30 Jun - Initial proposals (short abstract) due
  3. 21 Jul - Proposal acceptance
  4. 15 Sep - Accepted paper submissions

For all information, contacts and updates, see the OSDC conference web site at http://osdc.com.au/2008/.

Tuesday, February 5, 2008

PHP Ajax Frameworks

  • Based on the best practices of web development, thoroughly tried on several active websites, symfony aims to speed up the creation and maintenance of web applications, and to replace the repetitive coding tasks by power, control and pleasure.
  • Symfony provides a lot of features seamlessly integrated together, such as:
    • simple templating and helpers
    • cache management
    • smart URLs
    • scaffolding
    • multilingualism and I18N support
    • object model and MVC separation
    • Ajax support
    • enterprise ready

Tuesday, May 15, 2007

PHP Information

PHP Infosource new blog for PHP information.
Get a news, source code, open CMS information, PHP solutions etc. here.

Basic Concept:

PHP is a powerful server-side scripting language for creating dynamic and interactive websites.

PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code.

The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows.

Some Important sites of PHP:

  • http://www.w3schools.com/php/default.asp
  • http://www.php.net/
  • http://www.planet-source-code.com/URLSEO/vb/Tutorial/default!asp/lngWId!8/anyname.htm
  • http://www.learnphpfree.com/
Some Important forums:
  • http://forums.devnetwork.net/
  • http://www.phpfreaks.com/forums/
  • http://phpbuilder.com/board/
  • http://www.sitepoint.com/forums/forumdisplay.php?forumid=34
You can find some good scripts here:
  • http://www.freeprogrammingresources.com/phpsrc.html
  • http://www.sitepoint.com/article/highlight-source-code-php
  • http://www.googleduel.com/apiexample.php
  • http://www.hotscripts.com/