May
27
2011

PHP Forms for Absolute Beginners – I

PHP is a very powerful language to process HTML forms. A very common use of PHP forms is to collect information from the user and process that information for further use. PHP is extensively used for form processing like feedback, contact, sending emails and a lot more.

In this tutorial, I will explain you how to make a simple php form with add, view list, view, edit and delete features. This tutorial assumes basic knowledge of HTML and PHP. Please note that this tutorial is just for understanding and practice purpose, do not use this in any live site as it does not make use of any form validation and security.

I will introduce two methods for form processing in this tutorial.

1) Two separate php pages

2) A single php page

We generally use the latter but since this tutorial is dedicated to beginners, I decided to use both methods.

Basic Setup:

First we need to setup our database. The database and table names that I used are ‘db_table’ and ‘tbl_test’ respectively. You can see the query to create the table below. The code is pretty straight forward. If you have any problem understanding the code, please let me know in the comment section.

—- Database: `db_table`–

—- Table structure for table `tbl_test`–


CREATE TABLE `tbl_test` (  `profile_id` int(11) NOT NULL AUTO_INCREMENT,
`profile_name` varchar(40) NOT NULL,  `profile_class` varchar(30) NOT NULL,
`profile_sec` varchar(2) NOT NULL,  `profile_gender` varchar(1) NOT NULL,
`profile_desc` longtext NOT NULL,  PRIMARY KEY (`profile_id`) )

Now the css part.

style.css


html
{ height: 100%;}

*
{ margin: 0;
  padding: 0;}

body
{ font: normal .80em 'trebuchet ms', arial, sans-serif;
  background: F4F4EE;
  color: 5D5D5D;}

table
{	margin: 10px auto;}

table tr th, table tr td
{ background: 3B3B3B;
  color: FFF;
  padding: 7px 4px;}

table tr td

{ background: CCCCCC;
  color: 47433F;
  border-top: 1px solid FFF;}

Method I

Two separate pages: form and form confirmation

In this method we are going to use two files: form.php and form_confirm.php. We are processing our form in two steps: form.php gets data from the user and form_confirm.php stores the data into the database.

form.php




<html>
<head>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<title>Simple Form</title>
</head>

<body>
<!-- Create table; width = 400px -->
<table border="0px" width="400px">
<!-- form with method post  -->
<form action="form_confirm.php" method="post"></form>
<tbody>
<tr>
<td colspan="2" align="center">Form</td>
</tr>
<tr>
<td>Name:</td>
<td><input maxlength="30" name="txt_name" size="30" type="text" /></td>
</tr>
<tr>
<td>Class:</td>
<td><input name="txt_class" type="text" /></td>
</tr>
<tr>
<td>Section:</td>
<td><input maxlength="2" name="txt_sec" type="text" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><input name="opt_gen" type="radio" value="M" />Male
		<input name="opt_gen" type="radio" value="F" />Female</td>
</tr>
<tr>
<td>Short Description about yourself</td>
<td><textarea cols="30" rows="5" name="txt_yourself"></textarea></td>
</tr>
<tr>
<td> <input onclick="javascript:  document.location='viewform_list.php';"
name="view_list" type="button" value="view list" /></td>
<td> <input name="submit" type="submit" value="submit" /></td>
</tr>
</tbody>
</table>


 

Line 11: We have used action = “form_confirm.php” as the action sends the user to form_confirm.php page when the user clicks on submit button. We use POST method to process this form. There are two types of method; POST and GET. The POST method basically means that the content is passed to the script as input file where as in the GET method the content is passed as a part of the URL. In simple term, in GET method the values that we entered in the field appears in the URL whereas in POST method, the values remain hidden. To know more – link.

form_confirm.php



<html>

<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Confirmation Page</title>

<body>
<table colspan="2" width="200px" border="2" text-align="center">
<tr>
<td>Confirmation</td>
</tr>

<tr>
<td>
<?php
		$pname = $_POST['txt_name'];
		$pclass=$_POST['txt_class'];
		$psec= $_POST['txt_sec'];
		$poptgen = $_POST['opt_gen'];
		$pdesc= $_POST['txt_yourself'];

		$link=mysql_connect("localhost","root","root");
		$db=mysql_select_db("db_table",$link);

		$sql = "INSERT INTO tbl_test VALUES('','$pname','$pclass',
'$psec','$poptgen', '$pdesc')";
		mysql_query($sql) or die(mysql_error());

		$affRows=mysql_affected_rows();

		if( $affRows == 1) {
			echo "Profile added successfully";
		}

		else {
			echo "Profile cannot be added";
		}

?>
	</td>
  </tr>
 <tr>

<td align="center"><input type="button" name="view_list" value="view list"
onClick="javascript:  document.location='viewform_list.php';"></td>
  </tr>
</table>

</body>
</html>


 

Line 16 – 20 : The values that were entered in the text box in form.php are stored as an array in $_POST. Now we retrieve all the inputs and store them in separate variables.
Line 22 : Connecting to sql server with hostname, username and password. The default username and password for mysql is “root” and “”(blank). To know more – link.
Line 23 : Connecting to the database.
Line 25 : Using those variables to insert values directly into the table “tbl_test”.
Line 28 : mysql_affected_rows() gets the number of affected rows in the table from the sql operation to check if the values got inserted or not.

Method II

A single page: form

Here we use a single page (form.php) to process our form.

form.php


<html>

<?php 

if (isset($_POST['submit']))
	{
	$pname = $_POST['txt_name'];
	$pclass=$_POST['txt_class'];
	$psec= $_POST['txt_sec'];
	$poptgen = $_POST['opt_gen'];
	$pdesc= $_POST['txt_yourself'];

	$link=mysql_connect("localhost","root","root");
	$db=mysql_select_db("db_table", $link);

	$sql = "INSERT INTO tbl_test VALUES('','$pname','$pclass',
'$psec','$poptgen', '$pdesc')";
	mysql_query($sql) or die(mysql_error());

	$affRows=mysql_affected_rows();

		if( $affRows == 1) {
			echo "Profile added successfully";
		}

		else {
			echo "Profile cannot be added";
		}
}

?>

<head>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<title>Simple Form</title>
</head>

<body>

<table border="0" width="400">
<form action="form.php" method="post" name="index">

<tr>
	<td colspan="2" align="center">FORM</td>
</tr>

<tr>
	<td>Name: </td>
	<td><input type="text" name="txt_name" size="30" maxlength="30"/></td>
</tr>

<tr>
	<td>Stream: </td>
	<td><input type="text" name="txt_class" /></td>
</tr>

<tr>
	<td>Section: </td>
	<td><input type="text" name="txt_sec" maxlength="2" /></td>
</tr>

<tr>
	<td>Gender: </td>
	<td><input type="radio" name="opt_gen" value="M" />Male
		<input type="radio" name="opt_gen" value="F" />Female</td>
</tr>

<tr>
	<td>Short Description about yourself</td>
	<td><textarea name ="txt_yourself" cols="30" rows="5"></textarea></td>
</tr>

<tr>
	<td> <input type="submit" name="submit" value="submit" /></td>
	<td> <input type="button" name="view_list" value="view list"
	onClick="javascript:  document.location='viewform_list.php';"> </td>
</tr>

</form>
</table>

</body>
</html>


 

Line 5 : We check if the submit button is pressed or not. The isset() checks if the $_POST array has submit variable with boolean set to true or false. If true, the statements inside the if..else.. is executed. Note that the isset($_POST['submit']) is set to true only when the user clicks on submit.
Line 41 : The major difference in this statement is the action is set to itself or form.php. It means that when the user clicks on the submit button, he is redirected to the same page. We can use action=” instead of action=”form.php”.



action="<?php echo $PHP_SELF; ?>"


 

Output

Download

You can download the file here.

Next part

In this tutorial we have seen how we easily inserted information into the database. In the next we will see how to retrieve these information. We will make use of two steps: first to generate a list of all the stored values and then to show each individual data.

Next part -

PHP Forms for Absolute Beginners – II (View Post)

To stay updated, please follow @fortystones and @prashishh.

Subscribe to fortystones.
Follow @fortystones on Twitter.
Get updated from our Facebook Fanpage.

Share

11 Comments + Add Comment

Leave a comment

*