Wickham's HTML & CSS tutorial

Search | Home | PHP introduction

PHP code for a simple form

View in Firefox, Safari, Opera and IE but IE6 often needs different solutions. In general IE7 and IE8 display like Firefox apart from the HTML5 and CSS3 features. The IE9 & above updates are mainly related to HTML 5 and CSS3 issues and display to a large extent like other main browsers. Google Chrome is based on the same WebKit engine as Safari.

Some of the examples are provided just to show problems, others show solutions that work in most major browsers. Use the example that suits you.
red icon problems   gold icon warning: works in some situations or some browsers or needs care to display as you wish   green icon OK in Firefox, Safari, Opera, Google Chrome and IE

For the basic PHP codes see PHP introduction

This example will lead you through the PHP codes for a simple form

1 green icon Assume that you want to devise an online form for people to rate songs between 0 and 10 according to how much they like them and display the result on a webpage. In this simple example you can only rate one song at a time and then it will be overwritten by the next vote, but by sending results to a database you could record each vote and display on them on the same webpage if you wanted.

I have shown the form and the entire body markup code first so that you can get the general idea and then I explain each part lower down the page. Make sure you see the difference between curved brackets ( ) and curly brackets { } as it isn't very clear, but using zoom if you have it will make them more clear.

Please submit form.

Rating (out of 10 please):

The full code is:-

First code the html markup for the form:-

Notice that the action is to the same file in this case. The PHP code below is designed so that the server will start from the top, reach some PHP code which it doesn't at that stage have data for as the viewer has not yet submitted the form, so it gets a false result all the way through various tests (conditional statements) with "if" and "elseif" and finally the last command for "else" will display the form.

The viewer then fills in the form and submits it and the action starts the server process again but this time it has data so it works through each conditional statement. If it gets a true result it stops and an "echo" (print) displays the message on the page; if the answer is false it moves on to the next one. Most questions are asked to establish what you don't want, like "Is the number more than 10?" and if that is true the echo displays an error message. Eventually you ask a question that requires an answer that you do want and the echo displays the result if it is true. I have omitted the conditional statements temporarily and will cover them later.

It is possible to send the action to another page which will show when a true result is obtained, or display a separate error page, or to send the data to an email or database.

Each PHP code section starts with <?php and ends with ?> and double forward slashes like // are to include notes and comments that the processor ignores.

if(isset()) is the first conditional statement and begins with if and the isset refers to sendit which is the name of the submit button in the form. $_POST fetches the data from the form which has method="post". If the data "is set", ie is already processed and held in memory, the server will proceed with whatever instructions are inside { } curly brackets, but if not it will skip to the closing bracket where there is an else and an alternative which says Please submit form. Always make sure each opening bracket is closed.

Each section of code ends with a semicolon ; however, sections that are a sequence as part of the initial instruction like an if followed by a series of elseif or else statments are not separated by a ; semicolon which would stop that process.

Notice that echo tells the server to print the content to the screen and text should always be inside "..." and end with a semicolon ; to end the instruction. The whole of the echo code is normally enclosed in { } which are part of the isset function but only the opening { is shown; read the next paragraph for the reason. Html code tags like <p> can be coded between the "..." text double quote marks.

At this point the code should be followed by the form markup. It is possible to carry on within the PHP code after the message Please submit form but the form code has lots of characters like " which have meaning for the PHP processor so the characters would have to be disabled by placing a backslash in front like name=\"rating\" which gets messy so it's better to close the PHP, code the form and then reopen PHP for the final bit of code which is to close the curly bracket which was opened for the echo statement and then to close PHP.

The codes and conditional statements within the { } curly brackets relating to isset are designed to process the form data, not just to display the results but also to weed out rogue entries. Viewers cannot be trusted to fill in forms correctly, they may use alpha characters or minus signs or numbers larger than the stated limits or enter 02 instead of 2 or forget to fill in an input box and so on. Note that each item is ended with a semicolon ;

Variables

These are called variables and set up the relationship between the form's name and the variable which begins with $. The $_POST [] is called a superglobal and fetches the data from the form which has method="post". The form name like "rating" includes a string or text string and is in single quotes inside the square brackets above. The semicolon closes the code.

Arrays

These are both an array and each is setting up a new variable with various text strings included in "..." separated by a comma , so that the arrays can be used in further processing.

Functions

The function called str_replace or string replace, can compare the text strings created in the arrays and replace the first items in $ratinga with those in the second $ratingb if they are found in the variable $rating which is the third variable and which takes the text strings from the form. It has then created a new variable $rating2 for use elsewhere.

Conditional statements and functions

The conditional statements I have included are only a small selection of the available possibilities. They are inserted between the { } curly brackets relating to the isset conditional statement.

The above code is saying that if the value of the variable $rating (from text string "rating" in the form) is higher than the value of 10 and is true, use the echo statement to display the text on the screen and stop, if false, go on and process the next item.

eregi:- After the first if you use elseif for another conditional statement and else for the last one. eregi is a function for regular expression match (case insensitive) and compares what is found by the first part of the code with what is in the variable $rating and if true, echos the text. In this case [0-9] means look for numbers 0 to 9 inclusive in any position (ie 01, 4, 04, 94, 10 etc, although numbers over 10 have already been weeded out). Those are numbers that we want to be processed and we don't want the echo text to show, so the [^] in front means NOT, so what the code is looking for is everything that is not a number 0 to 9, in other words all alpha characters and any other characters like - or ? or " and the like. If it finds these it will be true and echo the message to use only numbers between 0 and 9 (I said 0 to 10 just to be more clear, as this will include 1 to 9).
elseif(...) is the conditional statement and inside is eregi('[^][0-9]' , $rating) which is the function.

strlen:- This is using the function strlen or string length which means that it is looking inside the value of the variable $rating for the text string and if it is more than two in length (not value) it is true and will echo the text. This weeds out entries like 003 or 00005. It could have been set as >1 to exclude 02 etc, but 10 is wanted as a valid number so in this case I had to use this conditional statement for numbers over 2 digits which still have a value less than 10 (values over 10 have already been weeded out and two digit numbers like 06 have already been replaced by single digit numbers in $rating2 which has not been used yet).

The strlen above is the conditional statement that actually echos the entries. It is saying that if the string length inside the variable $rating2 is true (in other words it is still valid, not having been weeded out earlier) then it should echo the message which uses the variables $item for the song name and $rating2 for the vote in the text. $rating2 has already been adjusted from $rating to replace all remaining two digit numbers like 07 with just 7. The backslashes in front of the " are so that the PHP processor doesn't think they are part of the PHP code and stop the echo text, but treats them as part of the html code within the text.
There still remains one possibility, that there are no numbers at all entered in the input box, so if this conditional statement is false it will move on to the next statement.

empty:- This is using the function empty($_POST['rating']) inside the elseif (...) and asks whether the string from the form sent by method="post" is true (empty). If true it echos the message which is followed by the form which is what happens before a viewer has entered any data. The false scenario is irrelevant at this stage as the previous statements should have covered entries in the input box.


In this example the form markup is coded after the PHP code but it could be first which then means slightly different PHP code which has to end with

which tells the server, after it has already run through all the code and got to the bottom without being able to process any form data, to process the page again from the top where it will reach the form markup and display it as it already knows that there is no data from the first time it processed the code. However, it is not always advisable to place the form first when processing data to the same page as the form markup is processed twice just to display it before the viewer has a chance to enter data and there is a danger of looping continuously until the browser cuts off.


Notes

View/Source or View/Page Source in browser menu to see all html code.

The body of this page has margin: 20px. The examples above are in a containing div with width: 730px; and margin: auto; so that the page centralises at large screen resolutions.

A lot of codes have been put in html tags in my examples rather than in a stylesheet or in a style in the head. I have done this for the convenience of the viewer so that most (but not all) codes are in one place and the stylesheet does not always have to be viewed in addition. When coding your own page you should try to put as much as possible in a stylesheet and link with id or class to the html tag.

Remember that when a Doctype is included above the head before the html tag (as it should be) then the overall width of a div is its defined width plus borders, margins and padding widths.

If there are differences between Firefox and IE6 that cannot be overcome with one code, code first to get a satisfactory solution in Firefox then create an IF style which will only apply to IE6:-
for instance, if margin-top: 20px; in Firefox needs to be margin-top: 30px; in IE6 then put the following in the head of the html/xhtml page:-
<!--[if ie 6]> <style type="text/css"> div { margin-top: 30px; } </style> <![endif]-->
or if there are many different styles, create a separate stylesheet:-
<!--[if ie 6]> <link rel="stylesheet" href="ie6.css" type="text/css"> <![endif]-->
IE6 will contain just the amended styles such as div { margin-top: 30px; } and others (no head or body tags or Doctype).

When looking at a page source for this site you may see code like &lt;p>Little Egret&lt;/p> instead of <p>Little Egret</p>. The code &lt; is because in that instance the code is to be displayed on the screen as text. If the < symbol was placed in the code a browser would activate the code and it would not display as text. Such code is not normally required when writing html code tags which are to be activated.

© Wickham 2009


top | Sitemap | Home | PHP introduction

 

Google
web www.wickham43.net/