Thursday, April 16, 2009

Storing user input into a database using PHP

TABLE CREATION

CREATE TABLE `employee` (
`id` int(10) default NULL,
`name` varchar(20) default NULL,
`salary` int(10) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

HTML CODE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: larger;
font-weight: bold;
color: #FF0000;
}
-->
</style>
</head>

<body>
<form action="insert.php" method="post" name="form1" target="_self" id="form1">
<label></label>
<p>
<label></label>
<label></label><label></label>
<span class="style1">Employee Details</span></p>
<table width="323" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="146"><label>ID</label></td>
<td width="171"><input type="text" name="idval" id="idval" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="nameval" id="nameval" /></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="text" name="salval" id="salval" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submitbutton" id="submitbutton" value="Submit Details" /></td>
</tr>
</table>
</form>
</body>
</html>

PHP CODE (insert.php)

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("employee",$con);
$idval=$_POST['idval'];
$nameval=$_POST["nameval"];
$salval=$_POST["salval"];
$query="insert into employee values($idval,'$nameval',$salval)";
mysql_query($query);
mysql_close($con);
include ("show.php");
?>

PHP CODE (show.php)

<?php

$con = mysql_connect("localhost", "root","");
mysql_select_db("employee",$con);
$query="select * from employee";
$result=mysql_query($query);
echo '<table border="1" align="center">';
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["salary"]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);

?>

No comments:

Post a Comment