<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $addrErr = "";
$name = $email = $address = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["address"])) {
$addrErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//db side
if ($name == '' || $email == '' || $address == '') {
echo 'plz fill the required field';
} else {
$dbhost = 'localhost:3036';
$dbuser = '*****';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO persons ' .
'(name, email, address) ' .
"VALUES ('$name', '$email', '$address')";
mysql_select_db('phpform');
if (!empty($name)) {
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
}
mysql_close($conn);
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span class="error">* <?php echo $nameErr; ?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email; ?>">
<span class="error">* <?php echo $emailErr; ?></span>
<br><br>
Address: <input type="text" name="address" value="<?php echo $address; ?>">
<span class="error">* <?php echo $addrErr; ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $address;
?>
</body>
</html>
Monday, 14 July 2014
Simple html form which captures Name, Email, Address, posts to a php program. The PHP program will validate, and store the information in the database.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment