Hi,
I am new in php.I do not want to use client side validation.When I click on submit button my data is keep submitting to database even after validation fail…Please help me…
I just want to use server side validation to stop data submission on invalid input
My codes:
[php]<?php
$name=$email=$telephone=$detail="";
$nameerr=$emailerr=$teleerr="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
$con=mysqli_connect('localhost','root','ricky','phpexample');
if(mysqli_connect_errno()){
echo "Unable to connect:".mysqli_connect_error();
}
$name=mysqli_real_escape_string($con,test_input($_POST["name"]));
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameerr = "Only letters and white space allowed";
}
$email=mysqli_real_escape_string($con,test_input($_POST["email"]));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "Invalid email format";
}
$telephone=mysqli_real_escape_string($con,test_input($_POST["telephone"]));
if(!ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $telephone)){
$teleerr="Invalid phone umber";
}
$detail=mysqli_real_escape_string($con,test_input($_POST["detail"]));
$sql="insert into contactus2(name,email,telephone,detail) values ('$name','$email','$telephone','$detail')";
if(!mysqli_query($con,$sql)){
die ('error:'.mysqli_error($con));
}
mysqli_close($con);
}
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
[/php]
[code]
.error{color: #f00;} </header>
</div>
<div id="div">
<nav id="nav1">
<?php
include "menu.php";
?>
</nav>
<div id="div1">
<table id="table1">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> ">
<tr><td></td> <td>Name:</td><td><input type="text" required name="name" placeholder="Name" value="<?php echo $name?>">
<span class="error"><?php echo $nameerr?></span></td><td></td></tr>
<tr><td></td><td>Email:</td><td><input type="email" required name="email" placeholder="Email address" value="<?php echo $email?>">
<span class="error"><?php echo $emailerr?></span></td><td></td></tr>
<tr><td></td><td> Phome Number:</td><td><input type="tel" required name="telephone" placeholder="Telephone Number" value="<?php echo $telephone?>">
<span class="error"><?php echo $teleerr?></span></td></tr>
<tr><td></td><td>Details:</td><td><textarea cols="10" rows="5" name="detail" <?php echo $detail?>></textarea><br></td><td></td></tr>
<tr><td></td> <td></td><td><input type="submit" value="Submit" ">
</div>
</body>
[/code]