Form validation without losing Form data - php

I've set up a form with validation in PHP which works fine. The issue I'm facing is that validation occurs once the submit button is clicked. The form values get erased when the submit button is clicked. If there is a validation error, the user needs to fill all the values again instead of just the error one. Is there a way that once submit button is clicked the form values don't get erased?
<tr>
<td><label for="email_address">Email Address:</label> <input type="text" name="email_address" id="email_address" required /></td>
</tr>
<tr>
<td><label for="password">Password:</label> <input type="password" size="25" maxlength="25" name="password" id="password" required /></td>
</tr>
<tr>
<td><label for="password2">Re-enter Password:</label> <input type="password" size="25" maxlength="25" name="password2" id="password2" required /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
<tr>
<?php
if(isset($_POST['submit'])){
$email_address = $_POST['email_address'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_address)) {
?>
<td><?php echo "Enter Valid Email Address"; ?></td>
<?php
}
elseif ($password2 !== $password) {
?>
<td><?php echo "Passwords don't match"; ?></td>
<?php
}

You need to echo out the user-entry into the value of the input tags. These kind of forms are called "sticky forms"(Since the user input sticks to the form after submitting it).Try doing something like this-
<input type="text" name="email_address" value="<?php echo (isset($_POST['email_address']))?$_POST['email_address']:'';?>" id="email_address" required />
Added this ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This basically echoes out the last entry made by the user into the value field. Try doing this in each of the input tags.

Related

The code is right but I can't enter a data into the database

I'm a beginner in php. The code seemed right but when I try to insert the data from the form to the database, it doesn't enter to the database. What is wrong with my code?
Here's my code
addemployee.php
echo '<form action="addemployee.php" method="POST">';
echo '<table align ="center">';
echo '<tr><td>First Name: </td> <td><input type="text" name="first" pattern="[A-Za-z]{1,}" title="A-Z only" required></td> </tr>';
echo '<tr><td>Middle Initial: </td><td><input type="text" name="middle"></td></tr>';
echo '<tr><td>Last Name:</td><td> <input type="text" name="last"></td></tr>';
echo '<tr><td>Contact Number:</td><td> <input type="tel" name="contact" maxlength="11"></td></tr>';
echo '<tr> <td>Province: </td><td> <input type="text" name="provincee"></td></tr>';
echo '<tr> <td>City: </td><td> <input type="text" name="cityy"></td></tr>';
echo '<tr> <td>Username:</td><td> <input type="email" name="usernamee"></td></tr>';
echo '<tr><td>Password:</td><td> <input type="password" name="pass"></td></tr>';
echo '</table>';
echo '<br> <input type="Submit" name="submitt">';
if(isset($_POST['submitt'])){
$firstname=$_POST['first'];
$middleinitial=$_POST['middle'];
$lastname=$_POST['last'];
$contactnumber=$_POST['contact'];
$province= $_POST['provincee'];
$city =$_POST['cityy'];
$username=$_POST['usernamee'];
$password=$_POST['pass'];
$type= 'employee';
$query=("INSERT INTO usertbl (fname,middeinitial,lname,contactnum,province,city,username,password,type) VALUES ('$firstname','$middleinitial','$lastname','$contactnumber','$province',
'$city','$username','$password','$type')");
mysqli_query($db, $query);
}
echo '</form>';
Please check the changes:-
addemployee.php
<!-- use html form not php generated form -->
<form action="addemployee.php" method="POST">
<table align ="center">
<tr><td>First Name: </td> <td><input type="text" name="first" pattern="[A-Za-z]{1,}" title="A-Z only" required></td> </tr>
<tr><td>Middle Initial: </td><td><input type="text" name="middle"></td></tr>
<tr><td>Last Name:</td><td> <input type="text" name="last"></td></tr>
<tr><td>Contact Number:</td><td> <input type="tel" name="contact" maxlength="11"></td></tr>
<tr> <td>Province: </td><td> <input type="text" name="provincee"></td></tr>
<tr> <td>City: </td><td> <input type="text" name="cityy"></td></tr>
<tr> <td>Username:</td><td> <input type="email" name="usernamee"></td></tr>
<tr><td>Password:</td><td> <input type="password" name="pass"></td></tr>
</table>
<br>
<input type="Submit" name="submitt">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
if(isset($_POST['submitt'])){
$firstname=$_POST['first'];
$middleinitial=$_POST['middle'];
$lastname=$_POST['last'];
$contactnumber=$_POST['contact'];
$province= $_POST['provincee'];
$city =$_POST['cityy'];
$username=$_POST['usernamee'];
$password=$_POST['pass'];
$type= 'employee';
$db = mysqli_connect ('hostname','username','password','dbname') or die(mysqli_connect_error()); // provide your details here
$query=("INSERT INTO usertbl (fname,middeinitial,lname,contactnum,province,city,username,password,type) VALUES ('$firstname','$middleinitial','$lastname','$contactnumber','$province',
'$city','$username','$password','$type')");
if(mysqli_query($db, $query)){
echo "Inserted successfully";
}else{
echo "error:-".mysqli_error($db);
}
}
?>
Note:- your code is open to SQLInjection. So read about prepared statements of mysqli_* Or PDO and use them.

MVC block has issue with form not submitting

Just some background. I'm using an MVC. My form is put in a div in my template. It posts to the same page where my controller catches it with an isset(), saves stuff to the database, and redirects to a welcome page.
EDIT: It posts everything like it should if I remove the action part of the form. Must be something pertaining to the way index.php reroutes it to ensure that the user has permission to go to that URL, etc. Still looking for a solution.
I've done some debugging and it is apparent that the variables are not showing up in the $_POST variable.
<form method="post" action="<?php echo BASE_URL; ?>/login/register">
<fieldset><legend>Person Info</legend>
<table>
<tr><td><label for="firstname" class="required">Firstname:</label></td>
<td><input name="firstname" id="firstname" type="text" value="<?php echo $firstname; ?>" /></td>
</tr>
<tr><td><label for="lastname" class="required">Lastname:</label></td>
<td><input name="lastname" id="lastname" type="text" value="<?php echo $lastname; ?>" /></td>
</tr>
<tr><td><label for="email">Email:</label></td>
<td><input name="email" id="email" type="text" value="<?php echo $email; ?>" /></td>
</tr>
<tr><td><label for="username" class="required">Username: </label></td>
<td><input name="username" id="username" type="text" value="<?php echo $username; ?>" /></td>
</tr>
<tr><td><label for="password" class="required">Password:</label></td>
<td><input name="password" id="password" type="password" value="<?php echo $password; ?>" /></td>
</tr>
<tr><td><label for="pass2" class="required">Confirm:</label></td>
<td><input name="pass2" id="pass2" type="password" value="<?php echo $pass2; ?>" /></td>
</tr>
</table>
<button type="submit" class="btn btn-custom-lighten">Submit</button>
<button type="button" class="btn"
onClick="parent.location='<?php echo BASE_URL; ?>/nonprofit/welcome'">
Cancel
</button>
<br>
<br>
<button type="button" class="btn btn-primary"
onClick="parent.location='<?php echo BASE_URL; ?>/nonprofits/register'">
Nonprofits Register Form
</button>
<br>
</fieldset>
</form>
You can see my names are consistent from the controller code.
public function register()
{
print_r($_POST);
if (isset($_POST['firstname'])) {
try {
$person = new Person();
$person->handleUpdate($_POST);
$person->setUsername($_POST['username']);
$person->setPassword($_POST['password']);
$person->save();
header('Location: '.BASE_URL.'/login/welcome');
exit();
}
catch (Exception $e) {
$_SESSION['errorMessages'][] = $e;
}
}
$this->template->blocks['content'][] = new Block('registerForm.inc',array('return_url'=>$this->return_url));
}
Any help would be appreciated, but it looks to be an issue with my form. My form does get rendered, it just doesn't submit.

text box value disappears/empties on PHP validation

Hi I have a structure as follows. The issue is once the error message is displayed, the text box content disappears and need to re-type a value again. I need to retain the original text box value/content as it is whilst the message is displayed. How do you think I should change? Thanks.
<?php
if(isset($_POST['subN'])) {
$InNo = $_POST['invc_no'];
$MSG = '';
if($InNo == "")
{$MSG = 'Invoice number is required';}
else
{//some code to save data to a database}
?>
<!DOCTYPE html>
<head><title></title></head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="msgBox"><?php if(!empty($MSG)) echo $MSG; ?></div>
<table>
<tr>
<td><input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php htmlentities('InNo')?>"></td>
<td><input type="submit" name="subN" id="subN" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>
Change
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php htmlentities('InNo')?>">
To
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php echo htmlentities($_POST['invc_no'])?>">
Second Solution:
Put as below
$InNo = ''; // if you doesn't put any value into text box, then you will get undefined error while you use this variable later on so give initial value to null
if(isset($_POST['subN'])) {
continue ....
}
else{
continue ..
}
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php echo htmlentities($InNo); ?>">
Use $_POST['inNo'] in your input box:
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?= $_POST['inNo'] ?>">
Your are not echoing the value, by the way.
You have missed to put echo there.
Change this,
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php htmlentities('InNo')?>">
To
<input type="text" id="invc_no" name="invc_no" size="15" class="colr" value="<?php echo htmlentities('InNo')?>">

PHP register script with sha256 encryption

I am making a register script that lets a user register for an account on a website. I decided to use sha256 to encrypt the password.
Here is my code:
// Set error message as blank upon arrival to page
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['Submit'])){
//Connect to the database through our include
require_once ('includes/connect.inc.php');
// Filter the posted variables
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = stripslashes($_POST['email']);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$email = strip_tags($email);
$town = preg_replace("[^A-Z a-z0-9]", "", $_POST['town']); // filter everything but spaces, numbers, and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$forename) || (!$surname) || (!$email) || (!$password) || (!$town)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$forename){
$errorMsg .= "--- Forename";
} else if(!$surname){
$errorMsg .= "--- Surname";
} else if(!$email){
$errorMsg .= "--- email";
} else if(!$password){
$errorMsg .= "--- password";
} else if(!$town){
$errorMsg .= "--- town";
}
} else {
$hash = hash("sha256", $password);
$sql = "INSERT INTO customers (forename, surname, email, password, town, registeredDate, active)
VALUES('$forename','$surname','$email', '$hash', '$town', GETDATE(), 'True')" ;
$stmt2 = sqlsrv_query($conn,$sql);
} // Close else after missing vars check
} //Close if $_POST
?>
<form action="join_form.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
</tr>
<tr>
<td width="163"><div align="right">Forename:</div></td>
<td width="409"><input name="forename" type="text"/></td>
</tr>
<tr>
<td width="163"><div align="right">Surname:</div></td>
<td width="409"><input name="surname" type="text"/></td>
</tr>
<tr>
<td><div align="right">Email: </div></td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td><div align="right"> Password: </div></td>
<td><input name="password" type="password" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td><div align="right">Town: </div></td>
<td>
<input name="town" type="text" />
</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
</form>
When I press Submit button nothing happens. I don't get an error message, but the record does not get added to the database either.
I know it has something to do with me using
$hash = hash("sha256", $password);
Maybe I put it in the wrong place or something?
I am very new to PHP.
I changed my code entirely and used params in order to add a record to the database
<?php
require_once ('includes/connect.inc.php');
if ($_POST['Register'] == "register")
{
$params = array($_POST['email']);
$sql= "SELECT * FROM customers WHERE Email=?";
$stmt = sqlsrv_query($conn,$sql,$params);
if(sqlsrv_has_rows($stmt))
{
// echo"<h2>You have already signed up with this email </h2>";
header('Location: register_login_forms.php?error=2');
die();
} else if($_POST['password'] != $_POST['password2'])
{
// echo"<h2>Wrong Passwod</h2>";
header('Location: register_login_forms.php?error=3');
die();
}
$pass = hash("sha256", $_POST['password']);
$params = array($_POST['forename'],$_POST['surname'],$_POST['email'],$pass, $_POST['phone'], $_POST['question'],
$_POST['answer']);
$sql="INSERT INTO customers (forename,surname,email,password,phone,secret_question, secret_answer,active,registeredDate)
VALUES (?,?,?,?,?,?,?,'True',GETDATE())";
$stmt=sqlsrv_query($conn,$sql,$params);
header('Location: registerSuccess.php');
}
?>
And here is the form
<Form name = "Register" action="register.php" method="POST" >
<label>Forename</label><br />
<input required title="Please only use Letters" type="text" pattern="\s*[A-z]+\s*" name="forename" /><br/>
<label>Surname</label><br />
<input required title="Please only use Letters" type="text" pattern="\s*[A-z]+\s*" name="surname" /><br/>
<label>Email</label><br />
<input required title="Please enter a Valid Email Address" type="email" name="email" /></br>
<label>Password</label><br />
<input required title="Please have a Password of Minimum of 6 Characters with Numbers" type="password" pattern="[A-z0-9]{6,20}" name="password" /></br>
<label>Confirm Password</label><br />
<input required title="Confirm Password" type="password" pattern="[A-z0-9]{6,20}" name="password2" /></br>
<label>Secret Question</label><br />
<input required type="text" name="question" /></br>
<label>Secret Answer</label><br />
<input required type="text" name="answer" /></br>
<label>Phone Number</label><br />
<input required title="Please only use numbers" type="text" pattern="\d+" name="phone" /></br>
<input type="hidden" name="Register" value="register">
<input class="button" type = "submit"/>
</Form>

PHP Validation Message appears on top of my user form

I'm having a problem with one of my PHP form validation scripts.
Basically, I have a form that when a user submits information it does validation checking (via PHP) and outputs the result (Success, Error1, Error2 etc) via an echo statement
However, after a user Submits the form (the action=same page ie. it posts to itself) the validation message appears at the top of the form or next to it. I want the echo message to appear under the form.
This is what is happening now in the page:
Error: Your password is incorrect
Username:
Email:
Password:
Submit Button
This is what I want it to look like:
Username:
Email:
Password:
Submit Button
Error: Your password is incorrect
Does anyone know how to remedy this?
Here is the code:
<form id="username_check" name="username_check" method="post">
<tr>
<td><b>Username:</b></td>
<td><input name="Username" type="text" class="textfield" id="Username"
value="<?php echo($_POST['Username']); ?>"
/>
</td>
</tr>
<tr>
<td><b>Email Address:</b></td>
<td><input name="email_address" type="text" class="textfield" id="email_address"
value="<?php echo($_POST['email_address']); ?>"
/>
</td>
</tr>
<tr>
<td><b>Password:</b></td>
<td><input name="PASSWORD" type="password" class="textfield" id="PASSWORD" />
</td>
</tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</form>
<?php
//If form was submitted
if (array_key_exists('submit',$_POST)){
//Do something
echo "Form validation here.....";
}
?>
This is dependent on the order of execution of the code. If you are using an IDE, set a breakpoint before the validation and step through. Otherwise, I'm pretty sure we'll need to see some of the code to get an idea of why this is happening.
Try:
<form id="username_check" name="username_check" method="post">
<table>
<tr>
<td><b>Username:</b></td>
<td><input name="Username" type="text" class="textfield" id="Username"
value="<?php echo($_POST['Username']); ?>"
/>
</td>
</tr>
<tr>
<td><b>Email Address:</b></td>
<td><input name="email_address" type="text" class="textfield" id="email_address"
value="<?php echo($_POST['email_address']); ?>"
/>
</td>
</tr>
<tr>
<td><b>Password:</b></td>
<td><input name="PASSWORD" type="password" class="textfield" id="PASSWORD" />
</td>
</tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</table>
</form>
<?php
//If form was submitted
if (array_key_exists('submit',$_POST)){
//Do something
echo "Form validation here.....";
}
?>
If you are calling the
echo $error_message;
before showing the form, then the message is displayed before the form.
If you want the error message after the form just move the echo command after the form is printed out.
Sounds like you are echo'ing out your error message, then echo'ing out the form.
Do it the other way around.
Don't echo the error save it in to a variable and print it behind the form print.
That way you can also check every time if an error occur during form validation, simple check if error-variable is emtpy/false

Categories