Web Technology - Old Questions
3. Construct a web page that takes name, address, and phone number from the user and stores this information in the database using server side script. Use JavaScript to validate form data for phone number.
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Registration</title>
</head>
<body>
<h2>Client Side Form Validation</h2>
<form name="signupForm" onsubmit="return validateForm();" method="POST" action="./formSubmit.php">
<div>
<label for="name">Please enter your name: </label>
<input type="text" name="name" id="name">
</div>
<div>
<label for="address">Please enter your address: </label>
<input type="text" name="address" id="address">
</div>
<div>
<label for="phoneNumber">Please enter your PhoneNumber: </label>
<input type="text" name="phoneNumber" id="PhoneNumber">
</div>
<div>
<input type="submit" name="signup" value="Signup">
</div>
</form>
<script>
function validateForm() {
if (document.signupForm.name.value == "") {
alert("Please provide your name!");
document.signupForm.name.focus();
return false;
}
else if (document.signupForm.address.value == "") {
alert("Please provide your address!");
document.signupForm.address.focus();
return false;
}
else if (document.signupForm.phoneNumber.value == "") {
alert("Please provide your PhoneNumber!");
document.signupForm.phoneNumber.focus();
return false;
}
else if (document.signupForm.phoneNumber.value.length < 10) {
alert('phoneNumber must be at least 10 digit long');
document.signupForm.name.focus();
return false;
}
return true;
}
</script>
</body>
</html>
//formSubmit.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webtech";
$tablename = "users";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = $_POST['name'];
$address = $_POST['address'];
$phoneNumber = $_POST['phoneNumber'];
//connect to database
$conn = mysqli_connect($servername, $username, $password) or die(mysql_error()); //Connect to server
mysqli_select_db($conn, $dbname) or die("Cannot connect to database"); //Connect to database
// Insert the values into database
mysqli_query($conn, "INSERT INTO ".$tablename."(name, address, phoneNumber) VALUES ('$name','$address', '$phoneNumber')");
Print '<script>alert("Congrats! Your Submission is Successfully Registered!");</script>';
?>