You are on page 1of 73

PHP, MySQL & Apache

For the project


AUTOMATION OF THE
ELECTION SYSTEM IN
INDIA
Presented By:
Arijit Chowdhury,
VIT University.
Introduction to PHP
What is PHP?

 PHP == ‘Hypertext Preprocessor’


 Open-source, server-side scripting language
 Used to generate dynamic web-pages
 PHP scripts reside between reserved PHP tags
 This allows the programmer to embed PHP
scripts within HTML pages

20/5/13
3
WhatisisPHP
What PHP(Cont’d)
(cont’d)
 Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
 Executed on the server-side
 Source-code not visible by client
 ‘View Source’ in browsers does not display the PHP
code
 Plethora of built-in functions allow for fast
development
 Compatible with many popular databases

20/5/13
4
What does PHP code look like?
 Structurally similar to C/C++
 Supports procedural and object-oriented
paradigm (to some degree)
 All PHP statements end with a semi-colon
 Each PHP script must be enclosed in the
reserved PHP tag
<?php

?>

20/5/13
5
PHP Overview
•Easy learning curve
•Syntax Perl- and C-like syntax. Relatively easy to learn.
•Large function library
•Embedded directly into HTML
•Interpreted, no need to compile
•Open Source server-side scripting language designed
specifically for the web.
•Conceived in 1994, now used on +10 million web sites.
•Outputs not only HTML but can output XML, images (JPG &
PNG), PDF files and even Flash movies all generated on the fly.
Can write these files to the filesystem.
•Supports a wide-range of databases (20 + ODBC).
•PHP also has support for talking to other services using
protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP.
Comments in PHP

 Standard C, C++, and shell comment


symbols

// C++ and Java-style comment

# Shell-style comments

/* C-style comments
These can span multiple lines */

20/5/13
7
Variables in PHP

 PHP variables must begin with a “$” sign


 Case-sensitive ($Foo != $foo != $fOo)
 Global and locally-scoped variables
 Global variables can be used anywher
 Local variables restricted to a function or class
 Certain variable names reserved by PHP
 Form variables ($_POST, $_GET)
 Server variables ($_SERVER)
 Etc.

20/5/13
8
Variable usage

<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable

$foo = ($foo * 7); // Multiplies foo by 7


$bar = ($bar * 7); // Invalid
expression ?>

20/5/13
9
Echo

 The PHP command ‘echo’ is used to output the


parameters passed to it
 The typical usage for this is to send data to the
client’s web-browser
 Syntax
 void echo (string arg1 [, string argn...])
 In practice, arguments are not passed in parentheses
since echo is a language construct rather than an
actual function

20/5/13
10
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable

echo $bar; // Outputs Hello


echo $foo,$bar; // Outputs 25Hello
echo “5x5=“,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>

 Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with
25
 Strings in single quotes (‘ ‘) are not interpreted or evaluated by PHP
 This is true for both variables and character escape-sequences (such as
“\n” or “\\”)

20/5/13
11
PHP Control Structures
•Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
•Grouped into conditional (branching) structures (e.g. if/else) and
repetition structures (e.g. while loops).
•Example if/else if/else statement:

if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
20/5/13 } 12
Functions
 Functions MUST be defined before then can be
called
 Function headers are of the format
function functionName($arg_1, $arg_2, …, $arg_n)

 Note that no return type is specified


 Unlike variables, function names are not case
sensitive (foo(…) == Foo(…) == FoO(…))

20/5/13
13
Functions example

<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
  return $arg_2;
}

$result_1 = foo(12, 3); // Store the function


echo $result_1; // Outputs 36
echo foo(12, 3); // Outputs 36
?>

20/5/13
14
PHP - Forms
•Access to the HTTP POST and GET data is simple in PHP
•The global variables $_POST[] and $_GET[] contain the request
data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">

<input type="submit" name="submit"


value="Submit">
<input type="submit" name="cancel"
value="Cancel">
20/5/13 </form>
15
PHP - Sessions
•Sessions store their identifier in a cookie in the client’s browser
•Every page that uses session data must be proceeded by the
session_start() function
•Session variables are then set and retrieved by accessing the
global $_SESSION[]

20/5/13
16
WHY PHP – Sessions ?
Whenever you want to create a website that allows you to store and
display information about a user, determine which user groups a person
belongs to, utilize permissions on your website or you just want to do
something cool on your site, PHP's Sessions are vital to each of these
features.

Cookies are about 30% unreliable right now and it's getting worse every
day. More and more web browsers are starting to come with security and
privacy settings and people browsing the net these days are starting to
frown upon Cookies because they store information on their local
computer that they do not want stored there.

PHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer.
PHP Sessions store the information on the web server in a location that
you chose in special files. These files are connected to the user's web
browser via the server and a special ID called a "Session ID". This is
nearly 99% flawless in operation and it is virtually invisible to the user.

20/5/13
17
Destroy PHP - Sessions
Destroying a Session
why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser. Well, imagine that you had
a session registered called "access_granted" and you were using that to
determine if the user was logged into your site based upon a username
and password. Anytime you have a login feature, to make the users feel
better, you should have a logout feature as well. That's where this cool
function called session_destroy() comes in handy. session_destroy() will
completely demolish your session (no, the computer won't blow up or self
destruct) but it just deletes the session files and clears any trace of that
session.
NOTE: If you are using the $_SESSION superglobal array like we are in
this tutorial, you must clear the array values first, then run
session_destroy.
Here's how we use session_destroy():

20/5/13
18
Saving Data in Text Files
 PHP has built in functions for File I/O processing
 fopen (..), fwrite(..), fclose(..), fflush(..),
file_get_contents(..)
 Using these pre-made functions, File I/O in PHP
is similar to that of C
 General Flow:
 Open file
 Read data
 Modify data
 Write data
 Close file

20/5/13
19
Saving Data in Text Files
Reading from a file
<?php
    $file = fopen("sample.txt", "r");
    while (!feof($file)) {
        echo fgets($file), "<BR>";
    }
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>

Writing to a file
<?php
    $file = fopen("agent.log", "a");
    fputs($file, $HTTP_USER_AGENT."\n");
?>

20/5/13
20
Saving Data in Text Files
Reading from a file
<?php
    $file = fopen("sample.txt", "r");
    while (!feof($file)) {
        echo fgets($file), "<BR>";
    }
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>

Writing to a file
<?php
    $file = fopen("agent.log", "a");
    fputs($file, $HTTP_USER_AGENT."\n");
?>

20/5/13
21
Saving Data in Text Files
Reading a File directly into Array or String

The file() function reads entire file into an array: array file (string
filename [, int use_include_path]) Each element of the array
corresponds to a line in the file, with the newline still attached.
You can use the optional second parameter and set it to "1", if you
want to search for the file in the include_path, too.

Example (read a web page into an array and print it out):


$fcontents = file ('http://localhost');
while (list ($line_num, $line) = each ($fcontents))
{ echo "Line $line_num: " . htmlspecialchars ($line) . "\n"; }

Example (read a web page into an array and join it to a string):


$fcontents = join ('', file ('http://localhost'));

20/5/13
22
Saving Data in Text Files: Example
<?php
$filename = 'test.txt'; /* Filename for writing. This is assumed to be in the same directory as
the script */
$somecontent = "Add this to the file\n"; // String to append to the file

// Let's make sure the file exists and is writable first.


if (is_writable($filename)) {
// Open the file in append mode ( ‘a’ ) so that the string being stored is written at the end of the
// file rather than replacing the existing text
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }
   // Write $somecontent to the opened file.
   if (fwrite($handle, $somecontent) === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }
     echo "Success, wrote ($somecontent) to file ($filename)";
  
   fclose($handle);
} else {
   echo "The file $filename is not writable";
} ?>

20/5/13
23
PHP - Benefits
•Easy, powerful, popular
•Server-side scripting language
•Supports many DB’s (not only MySQL)
•Platform Independent
•Web Server Independent
•Free and Open Source
PHP Overtakes Microsoft ASP as the Web’s Number 1
server side Web technology for the Internet.
•An April Netcraft surveys indicate 24 percent of the
37.6 million websites, or are running PHP scripts. PHP
adoption is growing by 6.5 percent each month. (9
million sites)
20/5/13
24
Introduction to MySQL
MySQL Overview

 Fast, free, stable database


 Syntax is similar to Oracle
 Many of the same features as Oracle
 Production version still missing subqueries,
stored procedures, and triggers
 Frequently used in conjunction with Linux,
Apache, and PHP

20/5/13
26
MySQL – Database Basics
•A relational database manager (MySQL) manages databases
which holds tables which has records (rows) with attributes
(columns)

•Each record must have a unique ID, also known as a


Primary Key. When used as an identifier in another table it’s
called a Foreign Key. Used for joins.

•Each attribute has to have a data type. (e.g. int, text,


varchar)

•A database language (SQL) is used to create and delete


databases and manage data

20/5/13
27
MySQL – Create Tables
 Table structure for following examples:
CREATE TABLE oscarpool ( CREATE TABLE
uid int(4) auto_increment, bestdirector (
username varchar(255), bdid int(4)
email varchar(255), auto_increment,
bestpicture int(2), name varchar(255),
PRIMARY KEY (uid) PRIMARY KEY (bdid)
) )
 Created two tables, ‘oscarpool’ & ‘bestdirector’ using:
(a) use MySQL either in line mode (cd c:\mysql\bin and mysql) or
(b) Use MySQL Control Center
(c) use phpMyAdmin tool

PhpMyAdmin is a tool written in PHP intended to handle the administration


of MySQL over the Web. Currently it can create and drop databases,
create/drop/alter tables, delete/edit/add fields, execute any SQL statement,
manage keys on fields, manage privileges,export data into various formats
http://localhost:8088/mysql/index.php
20/5/13
28
MySQL – INSERT
 Common SQL Statement: INSERT
INSERT INTO
oscarpool
(username,email,bestpicture)
VALUES
(‘dolsen',‘dave@usablecode.com',1)

 Creates a new record in the table ‘oscarpool’


 Text fields need to have ‘s.
 Tip: If you have an ‘ in your data you need to escape it before
inserting it. Can use the PHP function addslashes().
 Example: ‘John O\’Brien’

20/5/13
29
MySQL – SELECT
 Common SQL Statement: SELECT
SELECT uid,username
FROM oscarpool
 Selects the attributes ‘uid’ and ‘username’ from every
record in ‘oscarpool’
 SELECT is how you query the database. You can also:
 limit the number of records returned with LIMIT,
 limit retrieval to those records that match a condition
with WHERE,
 sort the data after the query has been evaluated using
ORDER BY
 Tip: To easily select every attribute replace ‘uid’ with ‘*’

20/5/13
30
MySQL – UPDATE
 Common SQL Statement: UPDATE

UPDATE oscarpool
SET email = ‘david.olsen@mail.wvu.edu’
WHERE uid = 1

 Updates the email address where ‘uid = 1’ in the table


‘oscarpool’
 In this case I know that uid 1 is what my record was. In
many cases you’d pass a uid variable from a form.

20/5/13
31
MySQL – DELETE
 Common SQL Statement: DELETE

DELETE FROM oscarpool


WHERE uid = 1

 Deletes the record where ‘uid = 1’ in the table ‘oscarpool’


 DELETE only removes the record from the table. To remove
an entire table from the database you need to use the SQL
statement DROP.
 Tip: To remove every record in a table but not remove the
table just don’t include the WHERE clause.

20/5/13
32
MySQL – JOIN
SELECT bd.name
FROM oscarpool op, bestdirector bd
WHERE op.uid = 1 and
op.bestdirector = bd.bdid

 Selects the name of the Best Director that the user


with ‘uid = 1’ has chosen
 bestdirector is a Foreign Key of the Primary Key for
the table BestDirector

20/5/13
33
MySQL – ERD
 Entity-Relationship (ER) Modeling
 ER Modeling is the simple and clear method of expressing the
design (relations) of a database between tables and attributes.
 Rectangles – Represent entities.
 Diamonds – Represent relationships
 between entities
 Ellipses – Represent attributes that
 describe an entity
 Lines – Connect entities to relationships.
 Can have annotation.
 M = many, 1 = one.
 Lines – Connects entities to attributes. No annotation.
 Entity = Table, Attributes = Attributes

20/5/13
34
MySQL – DB Access
<html>
<body>
<h1>A List of Users Who Have Signed Up For OscarPool</h1>
<?
$dbh = mysql_connect("localhost","root","")
or die("Couldn't connect to database.");
$db = mysql_select_db("test", $dbh)
or die("Couldn't select database.");
$sql = "SELECT username, email FROM oscarpool";
$result = mysql_query($sql, $dbh)
or die("Something is wrong with your SQL statement.");

while ($row = mysql_fetch_array($result)) {


$username = $row['username'];
$email = $row['email'];
echo '<a href="mailto:'.$email.'">'.
$username.'</a><br />\n';
}
?> Save it as data.php
</body>
</html>
20/5/13
35
MySQL - Benefits
•In 1996 T.c.X. DataKonsultAB , a consulting firm in Sweden
developed MySQL.
•The largest growing relational database out on the market as
it can handle large databases that can be accessed over the
Web - Meets the ANSI SQL92 regulations (SQL-Structured
Query Language)
•Mainly runs on UNIX-based environments, but also used on
windows
•One of the most used open source databases in the world.
•Capacity to handle 50,000,000+ records.
•Very fast command execution, perhaps the fastest to be
found on the market.
•Flexible and secure password system to protect your data -
powerful security system
•Fast, reliable, easy to use, and affordable!
•On-line help facility - (type –help or -?,)
•Comes with a source code
Introduction to Apache
WebServer
Benefits of Web Applications

•Free Infrastructure: A major benefit is that the whole


infrastructure is already in place and well developed. Only a web
browser is needed. The new applications can be available to all
the relevant users immediately – IT support staff do not have to
go to each client workstation to install the Client Software

• Free Upgrades: As the application resides on the server, new


versions will be immediately and simultaneously available to every
user. There is no need to distribute updated application files to
every user.

•Interchangeable components: It is possible to exchange


either the server or the browser without breaking the application.
Web Technolgies
Client-side
•HTML (HyperText Markup Language)
•CSS (Cascading Style Sheets)
•XML (Extensible Markup Language)
•DTD (Document Type Declaration)
•XSLT (Extensible Style Sheet Language Translator)
•JavaScript
•VBScript/Jscript
•Animation (Flash )
•Dynamic Hypertext Markup Language (DHTML –
HTML, JavaScript, CSS & Document Object Model
(DOM)
Web Technolgies
Server-side
o PHP
o ASP (Active Server Pages) & ASP.NET
o JSP (Java Server Pages)
o Java Servlets
o C++/Java
o PERL
o XML
Database
 ODBC
 JDBC
 OleDB
20/5/13
40
Open Source Software
 Software in a community that is:
 Freely Used (no warranty, no limits on usage)
 Source code is available for any modifications
 Freely Extended (must share source, represent original
works and owners)
 License is not specific to a product or restrict other
software and also technology neutral.

 There's always plenty of professional and peer support from


documentation and mailing lists.
 Runs on any Platform. Bugs are fixed rapidly, and requests for
features are always heard, evaluated, and if feasible,
implemented.
AMP
 One of the most powerful development models
for the Web has been the notion of “AMP.”

 AMP stands for “Apache / MySQL / PHP &


Perl working together.”
Apache is the MySQL is a very PHP / Perl is a
industry-leading popular general purpose
web server that database that scripting
runs a majority runs on most environment
of web servers operating widely used for
on the Internet. systems. building dynamic
web sites.
Together, they form the nucleus of a web application system.
www.easyphp.org -> contains the software needed for all three
packages. You can install and configure very easily. I am showing
the installation separately
Apache, MySQL and PHP (AMP)
Integration
User

Us
er
Apache - Benefits
•Apache is well supported - Most support for Apache is free and
available 24 hours a day via Internet mail or newsgroups.
•Apache is multi-platform - Apache can run on virtually any
hardware platform (from PCs to mainframes), and almost any operating
system, such as Linux, Windows, NetWare, Macintosh, xBSD, etc.
•Apache is secure - security holes are rare but when they exist they
are discovered and fixed quickly
•Apache is extensible - anyone can write modules that easily plug in
to Apache. If Apache doesn't do what you want or need it to do, anyone
with programming skills can write the modules you need.
•Apache is database-friendly - you can interface Apache with
virtually any commercial database, such as Oracle, Sybase, DB2, and
Informix, as well as free databases such as MySQL and Postgres.
•Apache is hardware-friendly - Apache generally consumes far fewer
hardware resources that commercial web servers.
•No Microsoft Viruses - Apache is immune to the Code Red, Nimda,
and other viruses that target at Microsoft Web servers.
20/5/13
44
Installation – Apache (ver 2.0.52)
•Go to http://httpd.apache.org/download.cgi

• If you are downloading the Win32 distribution,


please read these important notes at the website
http://apache.mirror.mcgill.ca/httpd/binaries/win32/
README.html

•Download the binary version

Win32 Binary (MSI Installer): apache_2.0.52-


win32-x86-no_ssl.msi
Installation – Apache (ver 2.0.52)
 Move to the folder where the
Apache is installed and double
click on the file to start the
installation.
 Welcome screen - Press Next
to continue
 Apache license – Accept the
terms and Press Next
 Brief intro – Read and Press
Next
 Server Information – Enter
admin user’s email
 Setup Type – Typical
 Destination Folder : leave to
the default and press Next
 Wait for installation to
complete
 You can change the settings in
httpd.conf file in conf folder
Starting Apache
 Find the port address
 Open httpd.conf and find the port number : 80, 8080 or 8088

 c:\program files\Apachegroup\Apache2\conf folder


 Starting Apache service
 C:Program
Files\ApacheGroup\Apache2\bin\ApacheMonitor.exe. You will
see at the task bar
 Open the monitor and start the apache service if it is not done
already
 Testing the Apache web server
 http://localhost:8088/  You may have a different port
number
 you will see the test web page.
Configuration - Apache
 Edit and save httpd.conf file:
 Alter Options Indexes FollowSymLinks into
Options -Indexes FollowSymLinks

 Reboot Apache (not computer)


Installation - MySQL
•Go to
http://dev.mysql.com/downloads/mysql/5.0.html and
move to Windows (x86)5.0.0a-alpha26.7M

•Click Download

•Create folder called mysql and Unzip the file

•Execute setup.exe

•Welcome screen – Press Next to continue


•Information: Note down and press Next
•Destination Folder: Default (c:\mysql)
•Wait for installation to complete - Press Finish
Starting MySQL

• Go to C:\mysql\bin
• Execute winmysqladmin.exe. You will be prompted for
username and password. Type as admin with password as
admin
•You will see the Traffic light signal on the task bar and
also the admin window
Configuration - MySQL
MySQL Control Center
•Graphical administrative interface for MySQL
database(s)

•Can administer several DB servers that are


hosted on different machines

•Download from
http://dev.mysql.com/downloads/other/mysqlc
c.html

•Execute the file


MySQL Control Center - Configuration
 Open program in programs menu

 Establish connection
to DB server

20/5/13
53
MySQL Control Center - Configuration
 in Databases ignore mysql; delete test
 in User Administration delete
 first two users and assign
 password to root users
 ignore Server Administration
 adapt connection (password)

20/5/13
54
Installation - PHP

•Download php 5.0 (binaries) from


http://ca3.php.net/get/php-5.0.2-
Win32.zip/from/a/mirror

•Unzip the folder to c:\php-5.0.2-Win32


Configuration- PHP
• Move to c:\php-5.0.2-Win32
• Rename php.ini-dist file to php.ini
• Copy php.ini to C:\Windows
• Copy php5ts.dll to C:\Windows\SYSTEM
• Go to Start-> All Programs -> HTTP Apache
Server 2.0.52-> Configure HTTP Server
-> Edit the Apache config.httpd config file
• Look for a section that contains a number of
LoadModule directives (from line number
131) as
# LoadModule foo_module modules/mod_foo.so
20/5/13
56
Installation & Configuration- PHP
• Add the line at the end as
LoadModule php5_module "c:/php-5.0.2-
Win32/php5apache2.dll“
• Search for AddType and insert the following lines
#AddType application/x-tar .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php
.phtml .php
AddType application/x-httpd-source
.phps
• Configure the path to php.ini
PHPIniDir "C:/php-5.0.2-Win32“
• Start Apache Server
20/5/13
57
Test PHP and Apache
•Test the Apache Server as
• Create php folder in
D:\SoftwareInstallation\ApacheGroup\Apache2\htdocs or where you have
installed Apache

•Create first.php in htdocs\php folder


(D:\SoftwareInstallation\ApacheGroup\Apache2\htdocs\php) with
the following lines:
<?php
phpinfo();
?>
•Open the browser and type the following link
http://localhost:8088/php/first.php
the port number 8088 may be different in your installation.
You will be prompted the php information on the browser.
How it works
References
•www.php.net <-- php home page
•http://www.phpbuilder.com/
•http://www.devshed.com/
•http://www.phpmyadmin.net/
•http://www.hotscripts.com/PHP/
•http://geocities.com/stuprojects/ChatroomDescription.htm
•http://www.academic.marist.edu/~kbhkj/chatroom/chatroom.htm
•http://www.aspfree.com/c/a/ASP-Code/Free-ASP-Based-Chat-Program/
•http://www.aus-etrade.com/Scripts/php.php
•http://www.codeproject.com/asp/CDIChatSubmit.asp
•www.php.net/downloads <-- php downlad page
•http://www.php.net/manual/en/install.windows.php <-- php
instllation manual
•http://php.resourceindex.com/ <-- PHP resources like sample
programs, text book referencs, etc.
•http://www.daniweb.com/techtalkforums/forum17.html  php
forums
20/5/13
60
For more information…

 http://www.php.net/manual/en/
 http://www.w3schools.com/php/default.asp
 http://www.zend.com/zend/tut/
 www.opensource.org

20/5/13
61
Sample Project with Codes
Sample Project

ONLINE
REGISTRATION

20/5/13
63
First Page
Here all the information regarding the user is entered and is updated
to the database on clicking the submit button. Validation is done by
checking whether the name and email fields are empty or not…

20/5/13
64
Invalid Information!
Validation Performed…
The user has to go back and fill up the necessary details…

20/5/13
65
User Registered
If all the information entered is valid, then the user is
registered.
i.e. the information is updated in the database.

20/5/13
66
Coding
test.html

<html>
<head>
<title> MyWebForm... </title>
</head>
<body bgcolor=brown>
<h1><font color=white>
Hello! This is ARIJIT CHOWDHURY...</h1>
<br><br>
<h2> Please fill up the following details in the form...</h2>
<br>
<h3> Please Note that the <font color=black>name</font> and <font color=black>emailID</font> are mandatory fields. i.e. they
must not be left empty...</h3>
</font>
<br>
<form action=submit.php method=post>
<table>
<tr>
<td><h3>Your Name:</h3></td>
<td><input type=text name="name"></td>
</tr>

67
Coding…
<tr>
<td><h3>Your email ID:</h3></td>
<td><input type=text name="mail"></td>
</tr>
<tr>
<td><h3>Your Mobile:</h3></td>
<td><input type=text name="mob"></td>
</tr>

<tr>
<td><h3>Your Age:</h3></td>
<td><input type=radio name=age value="Below 18"> Below 18</td>
<tr>
<td><input type=radio name=age value="18 to 25"> 18 to 25</td>
<td><input type=radio name=age value="25 to 40"> 25 to 40</td>
</tr>
<tr>
<td><input type=radio name=age value="40 to 60"> 40 to 60</td>
<td><input type=radio name=age value="Above 60"> Above 60</td>
</tr>

20/5/13
68
Coding…
<tr>
<td><h3>Your Sex:</h3></td>
</tr>
<tr>
<td><input type=radio name=sex value="male"> Male</td>
<td><input type=radio name=sex value="female"> Female</td>
</tr>
<tr>
<td><input type=reset></td>
<td><input type=submit value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

File saved as test.html

20/5/13
69
Coding…
submit.php

<?php

mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());

$name=$_POST['name'];
$mail=$_POST['mail'];
$mob=$_POST['mob'];
$age=$_POST['age'];
$sex=$_POST['sex'];

echo "<body bgcolor=green>";

if ((empty($name))||(empty($mail)))
{
echo "<h1><font color=white>'Please fill up the mandatory fields(Name,EmailID)...'</font></h1>";
echo "<form action=test.html method=post><input type=submit value=GoBack></form>";
}

20/5/13
70
Coding…
else
{
if ($sex=="male")
echo "<h1><font color=white>Thank You, Sir!</font></h1>";
elseif ($sex=="female")
echo "<h1><font color=white>Thank You, Madame!</font></h1>";
else
echo "<h1><font color=white>Thank You!</font></h1>";

echo "<h2><font color=white>These are the information you Provided...</font></h2><br><br>";


echo "<h2>Name:$name</h2>";
echo "<h2>email ID:$mail</h2>";
echo "<h2>Mobile:$mob</h2>";
echo "<h2>Age:$age</h2>";
echo "<h2>Sex:$sex</h2>";

$q1="insert into login values($name,$email,$mob, $age, $sex)";


$res= mysql_query($q1);

20/5/13
71
echo "<br><br><br><h1><font color=white>Thank You for Registering!<br> Your email ID $mail. Remember it for
logging in...</font></h1>";
}

?>

File saved as submit.php

20/5/13
72
THANK YOU

You might also like