Monday, December 28, 2009

States in Ajax

State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

Page Breaks

It is possible to give modern web browsers a "hint" to help them put page breaks in the right places when printing out web pages with Stylesheets. Here is an example:

<p style="page-break-before: always;">

This will force a page break when printing, before the start of this particular

element.

Not all web browsers support CSS perfectly. If you must have absolute layout control and are primarily concerned with printing, consider using PDF rather than HTML.

Wednesday, December 23, 2009

Days ago function

// convert a date into a string that tells how long ago that date was.... eg: 2 days ago, 3 minutes ago.
function ago($d) {
$c = getdate();
$p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
$display = array('year', 'month', 'day', 'hour', 'minute', 'second');
$factor = array(0, 12, 30, 24, 60, 60);
$d = datetoarr($d);
for ($w = 0; $w < 6; $w++) {
if ($w > 0) {
$c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
$d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
}
if ($c[$p[$w]] - $d[$p[$w]] > 1) {
return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
}
}
return '';
}

// you can replace this if need be. This converts my dates returned from a mysql date string into
// an array object similar to that returned by getdate().
function datetoarr($d) {
preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2}) ([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/", $d, $matches);
return array(
'seconds' => $matches[10],
'minutes' => $matches[8],
'hours' => $matches[6],
'mday' => $matches[5],
'mon' => $matches[3],
'year' => $matches[1],
);
}

Monday, December 21, 2009

Magic_quotes and Mysql_escape_string and mysql_real_escape_string

Magic_quotes basically runs all get, post, and request variables through add_slashes function. The add_slashes function itself, adds a backslash before a single quote (’), double quote(”), backslash (\), and Null byte. If magic_quote is turned off, you can get the same effect by running your varible through the add_slashes function.

Mysql_escape_string and mysql_real_escape_string are very similar. The only differences are that you can use mysql_escape_string while not connected to a database, and it doesn’t respect the current charset setting. PHP manual at php.org, suggest that you should use mysql_real_escape_string anytime you want to insert information in to a database. Both of these functions escapes backslashes (\), new rows (\r), new lines (\n), single (’) and double (”) quotes. They also escape the characters \x00, and \x1a.

Well magic_quotes is passive, meaning that it is an option that is turned on in your php config or htaccess file by adding magic_quotes_gpc = On. Mysql_escape_string and mysql_real_escape_string must be used along with a variable, like all other functions. If you were to use the mysql_real_escape_string, your code will look like this mysql_real_escape_string($var).

Thursday, December 17, 2009

Date Functions

Fetching records between two date ranges

We can collect records between two date fields of a table by using BETWEEN query. We can use this to get records between two years or between two month . We can combine all this and try for getting records between two date ranges.

Between two years

We will first start with displaying records between two years. Before that you can read on how to get year part from a date field. Now let us try to get records between year 2004 and 2005. Here is our query
SELECT * FROM `dt_tb` WHERE year( dt2 ) between 2004 and 2005
IN the above query dt2 is our date field and in the result both the years 2004 and 2005 will be included in our records.

Between two month ranges.

Now let us collect the records between two months. Note that if we are using only month in our between command then for any year the range of month we specified will be returned by the query. For example if we ask for records between Feb and Aug months then we will get records of between the month Feb and Aug for all the years. Here is the example.
SELECT * FROM `dt_tb` WHERE month(dt) between '02' and '08'
The above query will return us records of all the months between February and August of any year. We can specify the year also along with the months like this
SELECT * FROM `dt_tb` WHERE month(dt) between '02' and '08' and year(dt) between 2004 and 2005
There are more details on how to get the month part of any date field here.

Now let us move to select a range of records between two dates. Here is the sql for this
SELECT * FROM `dt_tb` WHERE dt BETWEEN '2005-01-01' AND '2005-12-31'

Here is the code for SQl dump of the file to create your table for testing.

CREATE TABLE dt_tb (
id int(2) NOT NULL auto_increment,
dt datetime NOT NULL default '0000-00-00 00:00:00',
dt2 date NOT NULL default '0000-00-00',
PRIMARY KEY (id)
) TYPE=MyISAM;


# Dumping data for table `dt_tb`

INSERT INTO dt_tb VALUES (1, '2004-10-26 00:00:00', '2005-01-25');
INSERT INTO dt_tb VALUES (2, '2004-05-05 23:56:25', '2005-06-12');
INSERT INTO dt_tb VALUES (3, '2005-12-08 13:20:10', '2005-06-06');
INSERT INTO dt_tb VALUES (4, '2003-05-26 00:00:00', '2007-12-18');
INSERT INTO dt_tb VALUES (5, '2007-12-18 00:00:00', '2003-08-16');

Getting the recent one month or year records from MySQL table

Some time we have to collect last 7 or 15 days or X days (or month, year or week) data from MySQL table. For example let us find out who are the new members joined in our forum in last week. One shop may be interested in knowing new products added in last one month. What are the books arrived in last one year. Here irrespective of the date values we want the records of last X days from today, or we can say that the records between today and last X days ( month , year or week) are required.

We will use the MySQL function CURDATE() to get the today's date.

To get the difference in today date and previous day or month we have to use the MySQL function DATE_SUB

DATE_SUB is a MySQL function which takes date expression, the interval and the constant to return the date value for further calculation.

Here are some sample queries on how to get the records as per requirements .

select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 15 DAY)


The above query will return last 15 days records. Note that this query will return all future dates also. To exclude future dates we have to modify the above command a little by using between query to get records. Here is the modified one.

SELECT * FROM dt_tb WHERE `dt` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 15 DAY ) AND CURDATE( )


Let us try to get records added in last one month

select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)


Here also future records will be returned so we can take care of that by using BETWEEN commands if required.

select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)


You can easily make out what the above query will return.

We can collect records between a particular date ranges by using between command and DATE_SUB. Here are some queries to generate records between two date ranges.

select * from dt_tb where `dt` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 3 MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 0 MONTH )


This query will return records between last three months. This query again we will modify to get the records between three moths and six months.

select * from dt_tb where `dt` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 6 MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 3 MONTH )


Now let us change this to get records between 6 month and 12 month.

select * from dt_tb where `dt` BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 12 MONTH ) AND DATE_SUB( CURDATE( ) ,INTERVAL 6 MONTH )


With this you can understand how the records between a month range or a year range can be collected from a table. Note that the months ranges are calculated starting from current day. So if we are collecting records of last three months and we are in 15th day of 9th month then records of 15th day of 6th month we will get but the records of 14th day of 6th month will be returning on next query that is between 3 months and 6 months.

Monday, December 14, 2009

DOCTYPE In Html

The doctype declaration should be the very first thing in an HTML document, before the tag.

The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.

The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers can render the content correctly.

A typical DOCTYPE you might see on an HTML document is the HTML 4.01 transitional DOCTYPE. The DOCTYPE for HTML 4.01 Transitional documents looks like this:

The DOCTYPE isn't exactly an HTML tag or XHTML element. Instead it is a declaration and always appears at the very top of your documents.

Parts of a DOCTYPE

A DOCTYPE is made up of the following parts:

  • !DOCTYPE
    The identifier. It indicates to the user-agent that the enclosed information will define the type of document of the page.
  • HTML
    The Top Element. This tells the browser what element to expect as the top-level element. For HTML and XHTML documents this element would be
  • PUBLIC
    The Availability. The most common DOCTYPES you will use will be publicly available - "PUBLIC". But you can also specify a local DTD with the "SYSTEM" key word.
  • "-//W3C//DTD HTML 4.01 Transitional//EN"
    The Formal Public Identifier. This entire string is what identifies the DOCTYPE.

The FPI is made up of these parts:

  • -
    Registration. If there is a plus-sign (+) here, that means that the organization is registered with the ISO. A minus-sign (-) indicates that it is not registered.
  • W3C
    The Organization. This is the group that owns and maintains the DOCTYPE being used.
  • DTD
    The Type. This defines the type of DOCTYPE used.
  • HTML 4.01 Transitional
    The Human-Readable Label. This is the label that tells you what DTD is being used. It is written so that humans, rather than computers, can understand it.
  • EN
    The Language. This is the language that the DTD is written in. It is not the language of the content of the page.

Block-Level and Inline Elements

One of the key concepts to understanding properly structured HTML is the idea of block-level and inline elements. These elements form a hierarchy within a document, and there are definite rules about how they are used, and which element can contain another. Violating these rules may not cause a problem in displaying your page, since most browsers do not implement the rules of HTML with any precision. But if you try to validate your code, a mistake in using these elements will definitely cause an error report.


Certain HTML elements that may appear in BODY are said to be "block-level" while others are "inline" (also known as "text level"). The distinction is founded on several notions:

Content model

Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.

Formatting

By default, block-level elements are formatted differently than inline elements. Generally, block-level elements begin on new lines, inline elements do not. For information about white space, line breaks, and block formatting, please consult the section on text.

Directionality

For technical reasons involving the [UNICODE] bidirectional text algorithm, block-level and inline elements differ in how they inherit directionality information. For details, see the section on inheritance of text direction.

Style sheets provide the means to specify the rendering of arbitrary elements, including whether an element is rendered as block or inline. In some cases, such as an inline style for list elements, this may be appropriate, but generally speaking, authors are discouraged from overriding the conventional interpretation of HTML elements in this way.

The alteration of the traditional presentation idioms for block level and inline elements also has an impact on the bidirectional text algorithm. See the section on the effect of style sheets on bidirectionality for more information.

So, looking at this crystal clear description, what does it mean? Several things. Let's look at each in order.

Containing

A block-level element may contain other block-level elements, or it may contain inline elements. But inline elements cannot contain block-level elements, only data or other inline elements. So a block-level element is "bigger" or "higher" in the hierarchy. It defines a larger section of of the page than an inline element does.

Spacing

Block-level elements generally begin on new lines. In practice, most browsers insert a blank line between any two block-level elements. So if you have a paragraph (block-level), and you end that paragraph and begin another paragraph, there will be blank line between them. Same thing between a header and a paragraph, between two headers, between a paragraph and a list, between a list and a table, etc. This is a useful clue as to what a block-level element is. You need these clues because it is very difficult to find a sensible list of what the block-level elements are.

Inline elements do not start on a new line. If you type out a paragraph, and decide to make one of the words italic, does the browser jump down a line for the italic word? No, it doesn't and this is a clue as well. The italic tag is an inline tag. So is bold, strong, em, a href, etc. None of these tags causes the browser to start a new line, so these are all inline elements.
A partial list of each type of element

With the clues we now have, let's compile a partial list of the elements on each type. First, the block-level elements:

  • div
  • h1...h6
  • p
  • ul
  • ol
  • li
  • table
  • tr
  • td
  • th
  • blockquote

Now, the inline elements:

  • i
  • b
  • a href
  • a name
  • em
  • strong
  • q

Now, these are partial lists. I have not had the time to compile a complete list, and with the move the XML I'm not sure it is even possible, since in XML you can create your own tags. But the rules are what matters in this case. And the status of some tags does not quite fit this model. A good example is the IMG tag, which manages to be both a block-level and an inline element, depending on where you put it. Don't worry about that, it only gives you a headache to think about it too much.

If you look at the list again, you may discern a trend. Block-level elements generally describe the structure of your data, while inline elements generally describe the appearance of your data. It isn't a perfect fit, but a good rule of thumb to use in getting used to these ideas.

The first rule is that an inline element cannot contain a block-level element. If you have an i tag, and inside of that a p tag, that is a no-no. But if you have an i tag, and inside of that a b tag, no problem. If you want your links to stand out by making them italic or bold, you can place an i tag or a b tag, or even both, inside of the a href tag, and as long as you nest them properly, it is perfectly valid. But you must be certain to do one thing: every inline element must be inside of a block-level element. The reason is the inline elements usually do not have any structural role to define, since that is handled by the block-level elements. That is why an a href tag all by itself is not proper. It can be contained by a p tag, or an li tag, or an h1 tag, to name a few, but left out by itself is not a good idea.

While inline elements can contain any other inline elements, with only the rules of proper nesting to worry about, the same cannot be said of block-level elements. Some are bigger than others. Top of the hierarchy is the div tag. This tag can contain any other block-level element. But you cannot contain a div inside another block-level element. So, placing a div tag inside of a p tag, or a table tag, is not proper. A div tag can contain multiple block-level elements, as well. You can have a few headers, several paragraphs, a list, and a table, all inside of one div tag set.

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

So a paragraph can only contain inline elements. If you want to start a list, you end the paragraph and then start the list as a new block-level element. Headers and lists should also be treated this way. They may contain inline elements, but not other block-level elements.

Form element

The <form> tag is used to create an HTML form for user input.

A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A forms can also contain select menus, textarea, fieldset, legend, and label elements.

Forms are used to pass data to a server.

Form attributes

1. action value = URL - It Specifies where to send the form-data when a form is submitted
2. accept MIME_type - Specifies the types of files that can be submitted through a file upload(image/gif, pdf, doc etc)
3. enctype
The enctype attribute specifies how form-data should be encoded before sending it to the server.

The form-data is encoded to "application/x-www-form-urlencoded" by default. This means that all characters are encoded before they are sent to the server (spaces are converted to "+" symbols, and special characters are converted to ASCII HEX values).
4. method get/post Specifies how to send form-data
5. name name Specifies the name for a form
6. target _blank/_self/_parent/_top framename Specifies where to open the action URL

Difference between mysql_connect() and mysql_pconnect()

mysql_connect() and mysql_pconnect() both are working for database connection but with little difference. In mysql_pconnect(), ‘p’ stands for persistance connection.

When we are using mysql_connect() function, every time it is opening and closing the database connection, depending on the request .

But in case of mysql_pconnect() function, First, when connecting, the function would try to find a (persistent) connection that’s already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the MYSQL server will not be closed when the execution of the script ends. Instead, the connection will remain open for future use (mysql_close() will not close connection established by mysql_pconnect()).

mysql_pconncet() is useful when you have a lot of traffic on your site. At that time for every request it will not open a connection but will take it from the pool. This will increase the efficiency of your site. But for general use mysql_connect() is best.

Friday, December 11, 2009

Altering the execution environment

string ini_get ( string varname)

string ini_set ( string varname, string newvalue)

void set_time_limit ( int seconds)

Once a script is running, you still have control over a number of system attributes that affect the way your script is executed. Using the ini_set() function you can temporarily change the execution environment, as if the php.ini file was different. Note that your change is only in effect for the current script, and will revert back when the script ends.

To use ini_set(), pass it a string for the value you want to change as its first parameter, and the new value to use as its second parameter - if successful it will return the previous value.

Here are some examples to get you started:
print ini_set("max_execution_time", "300") . "
";
print ini_set("display_errors", "0") . "
";
print ini_set("include_path", "0") . "
";
?>

If you want to read a php.ini value without altering it, use ini_get(), which takes the name of the value to read as its only parameter. Note that boolean values returned by ini_get() should be typecasted as integer because otherwise false values will be returned as an empty string. Here is an example of that in action:
print "Display_errors is turned on: ";
print (int) ini_get("display_errors");
?>

Note that many numerical values in php.ini are represented using M for megabyte and other shortcuts - these are preserved in the return value of ini_get(), which means you should not rely on these values to be plain numbers.

If you find yourself regularly using ini_set, you might find it best just to have multiple .ini files that record your set of changes. In this situation, try using the php_ini_loaded_file() function to check which configuration is loaded - it returns a string with the .ini filename.

The set_time_limit() function lets you arbitrarily set how long a script should take to execute. This value is usually set inside php.ini under the max_execution_time setting, however you can override that here. The function takes one parameter, which is the number of seconds you want the script to have, or you can pass 0 which means "let the script run as long as it needs". Here it is in action, setting the script execution time to 30 seconds:
set_time_limit(30);

Note that most web servers have their own time limit. In Apache, for example, this is set under "Timeout" in httpd.conf, and defaults to 300 seconds . If you use set_time_limit() to a value greater than Apache's timeout value, Apache will stop PHP before PHP stops itself. Also note that PHP may let some scripts go over the time limit if control is outside the script. For example, if you run an external program that takes 100 seconds and you have set the time limit to 30 seconds, PHP will let the script carry on for the full 100 seconds and terminate immediately afterwards. This also happens if you use the sleep() function with a value larger than the amount of time the script has left to execute.

How do i make max_upload file more than 2mb?

In the form have a hidden element

<input name="MAX_FILE_SIZE" value="30000" type="hidden">


and this to the section that handles the php upload Code:

ini_set ("post_max_size", 30000);
ini_set ("upload_max_filesize", 30000);

of course set 30000 to your desired maximum files

Uploading big files in PHP using .htaccess

Most of the web servers are configured such a way that a user can only upload the maximum file size of 2MB. So there might be the problem for the people who wants to upload the .pdf file of size around 15MB. But, you can increse the maximum upload file size limit by using .htaccess file.


1) Create a .htaccess file in the root folder of web server.

2) Put the following code in side the .htaccess file and save it.

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200

Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP. In the above .htaccess file, uploading capability is increased by the four parameter first one is maximum file size for uploading, second one is maximum size of the post data , third one is maximum time in seconds a script is allowed to run before it is terminated by the parser and last one is maximum time in seconds a script is allowed to parse input data such as like file uploads, POST and GET data.

You can change the above parameter to upload the bigger file size than 20MB.

Friday, December 4, 2009

What's New in PHP 5

PHP 5 release comes with a slew of new features aimed at simplifying development with PHP. With PHP 5 comes the introduction of exception handling, the Standard PHP Library (SPL), enhanced support for XML, reflection, and quite a few enhancements to the object oriented features of the language.

XML

PHP 5 by default installs XML support and offers a new extension, SimpleXML. All XML functions are now standardized on the libxml2 library and are fully W3C standards compliant. SimpleXML is quite possibly the most valuable addition to PHP in years, providing a traversable structure to work on XML documents, allowing you to simply change values in the structure and write the file out with only a few lines of code. The XML functionality that has been available through PHP in the past has been quite rudimentary and required a fair amount of programming work to use, so it is not uncommon to see PHP 4 applications using XML without ever touching the xml functions.

PHP 5 also offers a replacement extension for DOMXL (available in "experimental" form in PHP 4) with the DOM extension. This extension allows you to work on your XML files using the DOM object model and is superior to SimpleXML particularly when you are not certain what document format to expect with your application. While DOM is more powerful, SimpleXML is much quicker to implement and easier to get a handle on for beginner programmers. Both of the extensions are robust and well thought out, and whichever suits your programming needs and taste, you will be using a powerful extension that is light years beyond what was available in PHP 4.

Database Support

PHP 5 offers some big enhancements to its ability to interact with databases. The most significant addition is the embedded SQLite database, a quick, lightweight database engine made specifically for embedded applications. This means there is no RDBMS process running on the server; SQLite reads and writes directly to files on disk. This results in significantly lower memory overhead when the database is not being used, but major performance problems arise if the system is used in a high traffic environment. SQLite is intended for small scale use, as best I can gather.

When testing it with small tables and less than one thousand rows per table, it was comparable to MySQL in executing simple joins with only one concurrent request, but performance from SQLite degraded exponentially with five or more concurrent connections coming in, which makes perfect sense. This is a good database solution for a small site that needs minimal features and expects minimal usage. It could also be useful for storing embedded configuration data in a PHP 5 application that may house its main data store in another RDBMS, and only run small queries against SQLite. SQLite is relatively standards compliant with a few major exceptions, most notably the lack of an ALTER TABLE statement.

PHP 5 also introduces support for the MySQL 4.1 client library with the introduction of the mysqli extension. The mysqli extension provides some basic objects for working with the MySQL server. The mysqli class is used as a connection object and as the ability to open and close connections as well as get context and state information from the server. The mysqli_stmt class represents a prepared statement that allows you to execute “prepare” and “execute” queries against the database. Lastly, the mysqli_result object provides a cursor based interface for reading results, providing similar functionality to the functions available in the standard MySQL extension using a MySQL resource handle. The new extension also adds support for SSL and input/output parameters.

The last notable addition in the database area is enhanced support for Firebird/InterBase, an RDBMS that offers most ANSI SQL-92 features and runs on most operating systems. The ibase extension provides most of the same functionality for Firebird/InterBase as the new mysqli extension does for MySQL but in the same manner as the old MySQL extension - that is, no objects.

SPL: Exceptions and Iterators

PHP 5 comes with the Standard PHP Library (SPL), a collection of objects built to handle various tasks such as exception handling and object traversal (iteration). There are basically six groups of classes/interfaces available natively to the SPL.

1. Iterators: SPL provides built in iterators to assist in a common task - object traversal. Iterators provide a way to traverse an object’s contents without exposing the inner workings of the object to the outside world. Iterators can be built to work on any data structure and provide a standardized interface. Some of the iterator classes and interfaces available in the SPL are: Iterator, OuterIterator, RecursiveIterator, IteratorIterator, ParentIterator, SeekableIterator, NoRewindIterator, and InifiniteIterator.

Each iterator has a specific purpose and details can be found in the PHP manual.

2. Directories: Two directory classes are available in the SPL: DirectoryIterator and RecursiveDirectoryIterator. These classes allow iterator based directory traversal and eliminates the need for messy directory handles.

3. XML: There is one XML handling class in SPL, SimpleXMLIterator, which provides iteration over a simplexml object.

4. Arrays: SPL offers something that has long been in need in PHP - ArrayObject and ArrayIterator. These object provide, as you may have guessed, an array object as well as an object to traverse the contents of an array without making assumptions on the way the array is storing it's internal data.

5. Counting: The SPL interface Countable allows you to hook into the standard array function count(), meaning you can use the count() function on a user defined object and get a meaningful result by implementing the Countable interface. This is very useful for non-simple data structures.

6. Exceptions: Probably the biggest feature addition via the SPL, exceptions allow graceful error handling through try/catch blocks. The Exception class is simple to extend and the SPL provides a few standard classes of exceptions for common problems, such as LogicException, BadFunctionCallException, DomainException, OutOfRangeException, and InvalidArgumentException. Error handling has been a longtime problem in PHP and has resulted in some of the ugliest code I've ever seen, particularly using the PEAR error class. Exceptions should eliminate this sort of problem in the future.

OOP: Object Enhancements

PHP 5 makes leaps and bounds in its support for objects. Aside from all the new features, Zend claims to have addressed the performance problems involved with object creation and usage in previous versions of PHP, a fact that in itself should encourage more developers to use object-based PHP. PHP 5 offers enhancements in a few key areas including object autoloading, destructors, visibility, static methods, class constants, type hinting, interfaces, cloning, reflection and several magic methods.

Autoloading is a great new feature that provides a way for developers to make sure all dependencies for a class are in place before using it. If you attempt to instantiate a class that has not yet been defined, PHP 5 will call the __autoload() function as a last attempt to load the class before failing with an error. Since most developers put one class per file, and many classes often depend on another either by way of inheritance or encapsulation, __autoload() allows you to make sure all the necessary class files have been included. While PHP 4 had constructors, PHP 5 offers a new features: destructors. Destructors are called when an object is destroyed or all references to it have been removed. Destructors are implemented in classes by use of the __destruct function. The __construct function has also been introduced and takes precedence over the old-style constructor function. The old style still works, but it is recommended that __construct is used as it takes higher priority.

One of the biggest additions to PHP's support for objects is visibility modifiers, also known as access modifiers. The var keyword has been deprecated and class variables are now to be declared as public, private, or protected. Public class variables are available to any other part of the program. Private variables are only available to that class. Protected variables are available to a class as well as its child classes, unlike private which only allows the class itself to access the variable. Methods can also be declared as public, private, or protected, and if none are declared a method is assumed to be public. Access modifiers allow PHP programmers to programmatically hide the inner workings of one object from another by preventing other objects from accessing class data directly. PHP 5 also introduces the static keyword. Static methods are called without an object instance and calls to static methods are resolved at compile time, not runtime. Static properties are accessed by the :: operator, not ->, and the special variable $this is not available in static methods.

Not only can you declares constants in C-style syntax, const constant = 'constant value';, but a class can contain it's own constants and access them internally using self::constant. This simplifies management of constants and keeps them contained within the classes they belong to, preventing code clutter and conflicts with other constants in the same application that may need the same name but a different value. PHP 5 also allows type hints in method parameter declarations. If a parameter is given a type hint and an object of the wrong type is passed to it, PHP will generate a fatal error. It would be preferable for an exception to be thrown, but type hinting does at least allow responsibility to be placed in the calling code for making sure the proper data type is passed into a function call. Type hints can be used in any function, not strictly in class methods.

PHP 5 also introduces abstract classes and interfaces, which is probably THE most significant enhancement to the language. Abstract classes and interfaces allow high level design principles to be semantically applied to PHP classes. PHP includes three special method keywords, final, abstract and virtual, to facilitate the use of inheritance and interfaces. When a method is declared as final, it cannot be overridden by a child class. When a method is declared as abstract, it must be defined in a child class. When a method is declared as virtual, it may be inherited as is or overridden by a child class. When used in combination, abstract classes and interfaces enforce high level design throughout all levels of implementation and support properly coded objects. They can be used in excess, as can anything else, but used properly these are the most powerful tools available to object oriented developers.

The last features of note are object cloning, some more magic functions and the reflection class. Object cloning allows the implementation of a magic method, __clone() to define what exactly takes place when clone is called on an object. It allows developers to implement deep copying of object data when cloning without writing messy code. A few other noteworthy magic functions are __sleep() and __wakeup(), which are used in conjunction with serialize and unserialize to ensure proper destruction and recreation of resources used within an object. Additionally, the __toString magic method allows a class to decide how to react when it is used in string context. The reflection class works as the name implies; it allows developers to programmatically reverse-engineer classes, interfaces, functions and extensions. Reflection is a powerful tool in developing custom application frameworks.

Overall, PHP 5 offers dramatic improvements over PHP 4 in a lot of areas. These improvements are, by and large, geared toward advanced PHP developers. With the exception of the SimpleXML extension, most of the new functionality will probably have no appeal to the largest segment of the PHP programming population - that is, developers who look at PHP as a simple scripting language and use it to accomplish one task at a time.

Thursday, December 3, 2009

Types of errors in PHP

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 you can change this default behaviour.

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 behaviour is to display them to the user when they take place.

Wednesday, December 2, 2009

Span and Div Tags

The <span> and <div> tags are very useful when dealing with Cascading Style Sheets. People tend to use the two tags in a similar fashion, but they serve different purposes.

<div>

The <div> tag defines logical divisions (defined) in your Web page. It acts a lot like a paragraph tag, but it divides the page up into larger sections.

<div> also gives you the chance to define the style of whole sections of HTML. You could define a section of your page as a call out and give that section a different style from the surrounding text.

But that's not all it does! The <div> tag gives you the ability to name certain sections of your documents so that you can affect them with style sheets or Dynamic HTML.

One thing to keep in mind when using the <div> tag is that it breaks paragraphs. It acts as a paragraph end/beginning, and while you can have paragraphs within a <div> you can't have a <div> inside a paragraph.

The primary attributes of the <div> tag are:
style
class
id

Even if you don't use style sheets or DHTML, you should get into the habit of using the
tag. This will give you more flexibility when more XML parsers become available. Also, you can use the id and name attributes to name your sections so that your Web pages are well formed (always use the name attribute with the id attribute and give them the same contents).

Because the <center> tag has been deprecated in HTML 4.0, it is a good idea to start using
<div style="text-align: center;">
to center the content inside your div.

More About the <div> Tag
<span>

The <span> tag has very similar properties to the
tag, in that it changes the style of the text it encloses. But without any style attributes, the <span> tag won't change the enclosed items at all.

The primary difference between the
and <div> tags is that <span> doesn't do any formatting of it's own. The <div> tag acts includes a paragraph break, because it is defining a logical division in the document. The <span> tag simply tells the browser to apply the style rules to whatever is within the <span>.

The <span> tag has no required attributes, but the three that are the most useful are:
style
class
id

Use <span> when you want to change the style of elements without placing them in a new block-level element in the document. For example, if you had a Level 3 Heading (<h3>) that you wanted the second word to be red, you could surround that word with
<span style="color: rgb(255, 0, 0);">2ndWord</span>
and it would still be a part of the </h3><h3> tag, just red.

serialize and unserialize

serialize

serialize — Generates a storable representation of a value

string serialize ( mixed $value )

Generates a storable representation of a value

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize().


unserialize

unserialize — Creates a PHP value from a stored representation

mixed unserialize ( string $str )

unserialize() takes a single serialized variable and converts it back into a PHP value.

Difference Between InnoDB and MyISAM

  • The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
  • InnoDB supports some newer features: Transactions, row-level locking, foreign keys
  • InnoDB is for high volume, high performance

Most people use MyISAM if they need speed and InnoDB for data integrity. You can use more than one or any combination of these table types in your database. Remember to asses the needs of your application before building it. Even though MyISAM is faster than InnoDB in the MySQL world, InnoDB is fast compared to any database engine.With InnoDB you get transactions, speed and integrity three features not usually used in the same sentence.

InnoDB has been designed for maximum performance when processing large data volumes. Its CPU efficiency is probably not matched by any other disk-based relational database engine.

Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any size even on operating systems where file size is limited to 2GB.

Falcon (storage engine)

Falcon is a transactional storage engine for the MySQL relational database management system currently available for preview in the MySQL website. It is currently in the beta stage of development, being worked at in a development tree based on the MySQL 5.2 release, for use in the upcoming MySQL 6.0. It is based on the Netfrastructure database engine.

Architecture analysis shows an interesting mixture of possible performance properties, while low level benchmarks on the first alpha release in 5.1.14-falcon showed that Falcon performed differently from both InnoDB and MyISAM (the current MySQL storage engines). It did better in several tests, worse in others, with inefficient support for the MySQL LIMIT operation a limitation. Its biggest advantage though is known to be ease of use; Falcon requires minimum maintenance and designed to reconfigure itself automatically to handle all types of loads efficiently.

Difference between POST and GET methods of Submitting Forms

A major problem people have in designing / creating forms is to decide whether to use the GET or POST methods.

GET:
-----
1. URL Changes to the submitted script name, appended with a list
of each variable with the value.
2. Use only if the number of variable to be used in a form ar very less.
3. Never use GET forms when asking for login ID and passwords.
4. Even hidden variables are shown as a part of the URL.
5. A lot of webservers might complain about long URLs being submitted.
A lot of times a URL 255 char or more is a problem.

POST:
-----
1. This is the best way of submitting forms to the web server.
2. There is no limitation on the number of Variables passed from the form.
3. This is a transparent way of transmitting variables to the webserver
where hidden variable are always hidden!


Usage Example

<form method="get" action="testform.html"><span >

<input name="userselected" value="ProcessNow" src="../images/testbutton.gif" type="image">
<input name="id" value="101" type="hidden"> </form><span >


Once the form is submitted, the URL will show as below:

http://www.mywebsite.com/tests/testform.html?
id=101&userselected=ProcessNow&userselected.x=130&userselected.y=42

Notice how the 'id' is shown as a part of the URL. This is not always what you might have wanted. So, here the length of the URL should not be > 255 characters for it to be processed properly by all webservers.

Usage Example

<form method="post" action="testform.html"><span >

<input name="userselected" value="ProcessNow" src="../images/testbutton.gif" type="image">
</span> <span >


Once the form is submitted, the URL will still show:

http://www.mywebsite.com/tests/testform.html


GET Method:

1. All the name value pairs are submitted as a query string in URL.
2. It's not secured as it is visible in plain text format in the Location bar of the web browser.
3. As the data transfers through address bar (URL) there are some restrictions in using space, some characters like ampersand (&) etc in the GET method of posting data. We have to take special care for encoding data if such special characters are present.
4. Length of the string is restricted.
5. If method is not mentioned in the Form tag, this is the default method used.
6. If get method is used and if the page is refreshed it would not prompt before the request is submitted again.
7. One can store the name value pairs as bookmark and directly be used while sharing with others - example search results.
8. Data is always submitted in the form of text
9. If the response of the page is always same for the posted query then use GET example database searches

POST Method:

1. All the name value pairs are submitted in the Message Body of the request.

2. Length of the string (amount of data submitted) is not restricted.

3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser.

4. If post method is used and if the page is refreshed it would prompt before the request is resubmitted.

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

6. Data is submitted in the form as specified in enctype attribute of form tag and thus files can be used in FileUpload input box.