registration_form
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
You do
require('validation.php');
setting and checking alot of variables e.g.
$name = test_input($_POST["name"]);
$nameErr = "Only letters and white space allowed";
come back from require and overwrite $name with original posted values and do nothing with $nameErr
$name = $_POST['name'];
check the errors after the require
e.g.
require('validation.php');
$lsError = $nameErr . $emailErr . $userErr . $passwordErr;
if(trim($lsError) != '') {
echo $lsError ."<BR>";
echo "ALL FIELDS ARE NECESSARY";
}
else {
//rest of your insert
}
Related
registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<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 $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
index.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
</style>
</head>
<body>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = "";
$name = $email = $username = $password = $DateOfBirth = $department = $age = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$usernameErr = "username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password)) {
$passwordErr = "Password must be alphanumeric and atleast 6 characters
long!";
}
}
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "AGE is required";
} else {
$age = test_input($_POST["age"]);
}
if ($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "") {
$check = "SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli, $check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($da[0] > 1) {
echo "Username Already in Exists<br/>";
}
else {
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,
`Date_of_birth` , `department` ,`age`)
VALUES ('','" . $username . "', '" . $hashed_password . "', '" . $email . "' ,
'" . $name . "' , '" . $DateOfBirth . "' , '" . $department . "' , '" . $age . "')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px">
<h2>Registration Form</h2>
<p><span class="error">All fields are required </span></p>
<form method="post" action="">
Name:
<input type="text" name="name" style="margin-left: 52px">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email" style="margin-left: 48px">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
Username:
<input type="text" name="username" style="margin-left:26px">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
Password:
<input type="password" name="password" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
Date Of Birth :
<input type="date" name="Date_of_birth">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
Age :
<input type="number" name="age" style="margin-left:62px">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
Department :
<select name="department" style="margin-left:14px">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<input type="submit" name="submit" value="Register">
</form>
</div>
</body>
</html>
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'amith';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
i'm creating a simple php registration form, i only have one issue which is not getting fixed i.e., when any one while registering enters the same username then an error message should throw saying that username already taken i have tried with the above code but its not working. please can any one help me to fix my issue.
before
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` ,
`name` , `Date_of_birth` , `department` ,`age`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' ,
'".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."')";
You can write SQL to check if username is exist or not :
SQL : 'SELECT username from users where username = $username';
If this query returns result with count more than 0 then show an error message as 'This Username already exists';
If it gives you 0 results then proceed with INSERT functionality.
Before you insert the new user you can query for the username with a select like:
SELECT username FROM users WHERE username='$username'
If this query returns more than 0 rows the username exists already.
Hi you can try like this
variable should be like this $_POST['username']
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,`Date_of_birth` , `department` ,`age`) VALUES ('', ".$username.", ".$hashed_password.", ".$email." , ".$name." , ".$DateOfBirth." , ".$department." , ".$age.")";
An effective way to tackle this unique username problem is to validate the username at the time of entry from UI.
Step 1:in html input box there should be jquery or js function call to a php page with entered username as argument.
Step 2 the backend php scrpt will simple check the username in database and if exists the will return a JSON o/p that userbane alreasy exist else it will return true.
Step 3:show the message to on UI with simple Js and block further processing of form.
Also you must check the uniqueness of username after form submit and before insert into your data base table to avoid concurrent submit by two different user with same username.
Also if possible make sure username is primary key in your database table to avoid concurrent submit with same username problem,This will add another solid layer of protection at the bottom.
<input type="text" name="uname" id="uname" onblur="unameOnBlur(this.value);">
You can do it onkeyup or any suitable event also.
inside unameOnBlur make an ajax call like
$.ajax({
url: 'json_uname.php?uname=' + uname,
dataType: 'json'
}).done(function (j){
if(username unique)
//your action code
})
the above one is sample ajax call example
Json_uname.php page is simple to write to check against db.
Hi I'm trying to do a form with data validation before writing into database. But im not sure why the data validation is not working. Below is my codes
filename: bookoffer.php
$NameErr = $EmailErr = $DescriptionErr = "";
//$Name = $Email = $Description;
if (isset($_POST['Submit']))
{
$errors = array();
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
}
else
{
$Name = ($_POST['Name']);
//check if name only contain letter and white space
if (!preg_match("/^[a-zA-Z ]*$/",$Name))
{
$NameErr = "**Only letters and white space allowed**";
}
}
if (empty($_POST['Email']))
{
$EmailErr = "**Email is required**";
}
else
{
$Email = ($_POST['Email']);;
//check if e-mail address is well-formed
if (!filter_var($Email, FILTER_VALIDATE_EMAIL))
{
$EmailErr = "**Invalid email format**";
}
}
if (empty($_POST['Description']))
{
$Description = "**Description is required**";
}
else
{
$Description = ($_POST['Description']);
}
}
//if(count($errors)==0)
include 'database_connect.php'; //make database connection
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Description = $_POST['Description'];
$sql = "INSERT INTO books_offer (Name, Email, Description) values ('$Name', '$Email', '$Description')";
$redirect = true;
header('Location: Thank_you.php');
mysqli_query($conn, $sql) or die (mysqli_error($conn));
mysqli_close($conn);
?>
Here is the html file which is calling for bookoffer.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Please Offer Your Book</h2>
<form id="bookoffer" method="post" action="bookoffer.php" >
<p><span class="error"> <font color="red">*required field.</font></span></p>
Name<font color="red">*</font> <input type="text" name="Name" >
<span class="error"> <?php echo $NameErr;?></span>
<br></br>
Email<font color="red">*</font> <input type="text" name="Email" >
<span class="error"> <?php echo $EmailErr;?></span>
<br></br>
Description<font color="red">*</font><textarea name ="Description" rows="5" cols="40" ></textarea>
<span class="error"> <?php echo $DescriptionErr;?></span>
<br></br>
<input type="submit" name="submit_form" value="Submit" />
</form>
</body>
</html>
You're not populating your $errors array so the if statement you've commented out will always be true. You are storing your errors in individual variables. One option would be to change
$errors = array();
to
$errors = false;
then, when you are setting the error variables add a line to each one to set $errors to true, one example,
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
$errors = true; // this line added
}
You can now update your commented out if statement to
if ($errors) {
I'm new to PHP but I have some experience with HTML and JavaScript. This is my webpage, it's a simple register screen.
<!DOCTYPE html>
<html>
<head>
<style>
.error{color: #FF0000;}
</style>
</head>
<body>
<?php
$name = $password = $confirmPassword = $email = $phone = "";
$nameErr = $passwordErr = $confirmPasswordErr = $emailErr = $phoneErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
//echo "insdie if";
if(empty($_POST["name"])){
$nameErr = "Name is required";
}else {
$name = $_POST["name"];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if($_POST["password"]){
$nameErr = "password is required";
if(!$_POST["confirmPassword"]){
$confirmPasswordErr = "Confirm password doesn't match password.";
}
}else {
$password = $_POST["password"];
if($password < 8){
$passwordErr = "Password should contain more than 8 characters";
}else
{
if(empty($_POST["confirmPassword"])){
$confirmPasswordErr = "Confirm password and password dont match";
}else {
$confirmPassword = $_POST["confirmPassword"];
if($confirmPassword != $password){
$confirmPasswordErr = "Confirm password and password dont match";
}
}
}
}
if(empty($_POST["email"])){
$nameErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
}
echo "".$name."";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h1>Register to CabsOnline</h1>
<p>Please fill th fields below to complete your registration</p>
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/><span class="error"><?php $nameErr;?></span></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/><span class="error"><?php $passwordErr;?></span></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirmPassword"/><span class="error"><?php $confirmPasswordErr;?></span></td>
</tr>
<tr>
<td>Emal:</td>
<td><input type="text" name="email"/><span class="error"><?php $emailErr;?></span></td>
</tr>
<tr>
<td>phone:</td>
<td><input type="text" name="phone"/><span class="error"><?php $phoneErr;?></span></td>
</tr>
</table>
<br/>
<input type="submit" value="Register"/>
<br/>
<h4>Already registered?</h4>Loging here
</form>
</body>
The code doesn't add the validation and I can't find out why. What do I have to do to get the value from the textboxes only when submit is clicked? I've changed it around but I just can't find an answer.
You need to actually echo the strings.
<?php $nameErr;?>
on its own doesn't do anything, it should be
<?php echo $nameErr;?>
your validation is working fine but the issue is that you are not printing the err msgs... like <td><input type="text" name="name"/><span class="error"><?php $nameErr;?></span></td> here you are not printing the value of $nameErr you need to echo the value of $nameErr like this
<td><input type="text" name="name"/><span class="error"><?php echo $nameErr;?></span></td>
do this
if(isset($_POST['name'])){
if($_SERVER["REQUEST_METHOD"] == "POST"){
//echo "insdie if";
if(empty($_POST["name"])){
$nameErr = "Name is required";
}else {
$name = $_POST["name"];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if($_POST["password"]){
$nameErr = "password is required";
if(!$_POST["confirmPassword"]){
$confirmPasswordErr = "Confirm password doesn't match password.";
}
}else {
$password = $_POST["password"];
if($password < 8){
$passwordErr = "Password should contain more than 8 characters";
}else
{
if(empty($_POST["confirmPassword"])){
$confirmPasswordErr = "Confirm password and password dont match";
}else {
$confirmPassword = $_POST["confirmPassword"];
if($confirmPassword != $password){
$confirmPasswordErr = "Confirm password and password dont match";
}
}
}
}
if(empty($_POST["email"])){
$nameErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
}
echo "".$name."";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
}
this will check if the form has been submitted or not and set the err messages only if the form is submitted
answer of #iainn is correct.
Additionally you can use client side validations using Javascript / jQuery which will prevent page reloading each time.
Use
<form method="post" name="formname" onsubmit="return validateform()">
OR
<input type="submit" onclick="validateform()" />
then add
<script type="text/javascript">
function() validatefrom(){
//your javascript validations
}
</script>
in header or footer part of document and write your javascript validations.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}