User registration form not working as it such php - php

I have create a form with html and php that allows a user to create an account and their information is stored within a mysql database.
The forms works and the user is able to create an account. However if the user clicks the submit button without filling in the form it seems to display that the email address has already been added.
I can't seem to see what is wrong.
My php code
<?php
session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
include "connect.php";
if (isset($_POST["submit"])) {
$error = array(); // Declare An Array to store any error message
$title = $_POST['title'];
$address2 = $_POST['up_address2'];
if(empty($_POST['up_first_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your First Name'; // add to array "error"
} else {
$firstName = $_POST['up_first_name']; // else assign it to a variable
}
if(empty($_POST['up_last_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your Last Name'; // add to array "error"
} else {
$lastName = $_POST['up_last_name']; // else assign it to a variable
}
if(empty($_POST['up_email'])) { // if no name has been supplied
$error[] = 'Please Enter Your Email'; // add to array "error"
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['up_email'])) {
// regular expression for email validation
$email = $_POST['up_email'];
} else {
$error[] = 'Your email is invalid';
}
}
if(empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password';
} else {
$password = $_POST['up_password'];
}
if(empty($_POST['up_date_of_birth'])) {
$error[] = 'Please Enter Your Date Of Birth';
} else {
$dateOfBirth = $_POST['up_date_of_birth'];
}
if(empty($_POST['up_number'])) {
$error[] = 'Please Enter Your Contact Number';
} else {
$number = $_POST['up_number'];
}
if(empty($_POST['up_address'])) {
$error[] = 'Please Enter Your First Line of Your Address';
} else {
$address = $_POST['up_address'];
}
if(empty($_POST['up_country'])) {
$error[] = 'Please Enter Your Home Country';
} else {
$country = $_POST['up_country'];
}
if(empty($_POST['up_postcode'])) {
$error[] = 'Please Enter Your Postcode';
} else {
$postcode = $_POST['up_postcode'];
}
if(empty($error)) // send to Database if there's no error
{
// If everything is ok...
// Make sure the email address is avilable:
$query_verify_email = "SELECT * FROM user WHERE Email ='$email'";
$result_verify_email = mysqli_query($con, $query_verify_email);
if(!$result_verify_email) {
echo 'Database Error Occured';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email.
$query_insert_user = "INSERT INTO user (Title, FirstName, LastName, Email, Password, DataOfBirth, ContactNumber, Address, Address2, Country, Postcode)VALUES ('$title', '$firstName', '$lastName', '$email', '$password', '$dateOfBirth', '$number', '$address', '$address2', '$country', '$postcode')";
$result_insert_user = mysqli_query($con, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system </div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
}
?>
My html form
<form name="signup" id="signup" action="create_account.php" method="post">
<label for="title">Title</label>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
</select>
<br>
<label for="up_first_name">First Name</label>
<input type="text" name="up_first_name" id="up_first_name" placeholder="First Name" />
<br>
<label for="up_last_name">Last Name</label>
<input type="text" name="up_last_name" id="up_last_name" placeholder="Last Name" />
<br>
<label for="up_email"> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password">Password</label>
<input type="password" name="up_password" id="up_password" placeholder="Password" />
<br>
<label for="up_date_of_birth">Date Of Birth</label>
<input type="text" name="up_date_of_birth" id="up_date_of_birth" placeholder="dd/mm/yyyy" />
<br>
<label for="up_number">Contact Number</label>
<input type="text" name="up_number" id="up_number" placeholder="+44 0000 000000" />
<br>
<label for="up_address">Address</label>
<input type="text" name="up_address" id="up_address" placeholder="Address" />
<br>
<label for="up_address2">Address 2 (optional)</label>
<input type="text" name="up_address2" id="up_address2" placeholder="Address 2" />
<br>
<label for="up_country">Country</label>
<input type="text" name="up_country" id="up_country" placeholder="Address 2" />
<br>
<label for="up_postcode">Postcode</label>
<input type="text" name="up_postcode" id="up_postcode" placeholder="Postcode" />
<br>
<input id="submit" name="submit" type="submit" value="Register My Account" id="myButton" class="btn btn-primary"/>
</form>

Related

Errors while submitting the form ( php & bootstrap)

I'm an intern at the company right now, and I've to create registration and login form for the website.
Currently I'm facing the problem with registration.
this is the errors
I declared everything like in the tutorials but still getting these errors and can't figure out it.
this is the php script:
<?php
//connection to database
include('connection.php');
if ($_SERVER['REQUEST_METHOD']=='POST'){
//Validation for Username
$errors = array();
if(empty($_POST['user_name'])){
$errors['user_name'] = 'Please fill in your Username';//Username
}else{
$user_name = mysqli_real_escape_string($con, trim($_POST['user_name']));
//validation to check if the username posted is in use.
if($check = $connection->query("SELECT * FROM student WHERE username = '$user_name'")){
if($check->num_rows){
$errors['user_name'] = 'Username in use';
}
}else{
$errors['user_name'] = 'the query did not work';
}
}
//validation for password
if(empty($_POST['pword'])){
$errors['pword'] = 'Please fill in password';
}else{
$pword = $_POST['pword'];
}
//checking if the password ented in verify password is matching the password field
if(empty($_POST['pwordConfirm'])){
$errors['pwordConfirm'] = 'Please verify password';
}else{
$pwordConfirm = $_POST['pwordConfirm'];
if($pword!=$pwordConfirm){
$errors ['pwordConfirm'] = 'passwords do not match';
}else{
$password = mysqli_real_escape_string($connection,trim($_POST['pword']));
// $password = sha1($password);
}
}
// validation for name textfield
if(empty($_POST['fname'])){
$errors['fname'] = 'Please fill in your name ';
}else{
$fname = mysqli_real_escape_string($connection,trim($_POST['customer_name']));
}
// validation for passport textfield
if(empty($_POST['passport'])){
$errors['passport'] = 'Please fill in your passport ';
}else{
$passport = mysqli_real_escape_string($connection,trim($_POST['passport']));
}
//validation for email
if(empty($_POST['email'])){
$errors['email'] = 'Please fill in your email';
}else{
$email = mysqli_real_escape_string($connection,trim($_POST['email']));
if($check = $connection->query("SELECT * FROM customer WHERE email = '$email'")){
if($check->num_rows){
$errors['email'] = 'Email in use';
}
}else{
$errors['email'] = 'the query did not work';
}
}
//validation for phone no
if(empty($_POST['mobinput'])){
$errors['mobinput'] = 'Please fill in your phone';
}else{
$mobinput = mysqli_real_escape_string($connection,trim($_POST['mobinput']));
}
//validation for phone no
if(empty($_POST['homemobinput'])){
$errors['homemobinput'] = 'Please fill in your phone';
}else{
$homemobinput = mysqli_real_escape_string($connection,trim($_POST['homemobinput']));
}
//validation for phone no
if(empty($_POST['dob'])){
$errors['dob'] = 'Please fill in your phone';
}else{
$dob = mysqli_real_escape_string($connection,trim($_POST['dob']));
}
//validation for gender column to be selected.
if(empty($_POST['sex'])){
$errors['sex'] = 'Please fill in your gender';
}else{
if( $_POST['sex'] == 'default')
{
$errors['sex'] = 'Please select your gender';
}
else{
$gender = mysqli_real_escape_string($connection,trim($_POST['sex']));
}
}
//validation for mstatus
if(empty($_POST['mstatus'])){
$errors['mstatus'] = 'Please fill in your phone';
}else{
$mstatus = mysqli_real_escape_string($connection,trim($_POST['mstatus']));
}
//validation for education
if(empty($_POST['education'])){
$errors['education'] = 'Please fill in your phone';
}else{
$education = mysqli_real_escape_string($connection,trim($_POST['education']));
}
//validation for occupation
if(empty($_POST['occupation'])){
$errors['occupation'] = 'Please fill in your phone';
}else{
$occupation = mysqli_real_escape_string($connection,trim($_POST['occupation']));
}
//validation for address
if(empty($_POST['address'])){
$errors['address'] = 'Please fill in your address';
}else{
$address = mysqli_real_escape_string($connection,trim($_POST['address']));
}
//validation for wmcauin
if(empty($_POST['wmcauin'])){
$errors['wmcauin'] = 'Please fill in your phone';
}else{
$wmcauin = mysqli_real_escape_string($connection,trim($_POST['wmcauin']));
}
//validation for tp
if(empty($_POST['tp'])){
$errors['tp'] = 'Please fill in your phone';
}else{
$tp = mysqli_real_escape_string($connection,trim($_POST['tp']));
}
//validation for wauinmassage
if(empty($_POST['wauinmassage'])){
$errors['wauinmassage'] = 'Please fill in your phone';
}else{
$wauinmassage = mysqli_real_escape_string($connection,trim($_POST['wauinmassage']));
}
//validation for hduhabttbc
if(empty($_POST['hduhabttbc'])){
$errors['hduhabttbc'] = 'Please fill in your phone';
}else{
$hduhabttbc = mysqli_real_escape_string($connection,trim($_POST['hduhabttbc']));
}
if(empty($errors)){
$query = "INSERT INTO student ";
$query .= "(`Student_id`, `Full_Name`, `Adress`, `Ic_Passport_no`, `Date_of_Birth`, `Mobile_No`, `Home_No`,
`Email`, `Marital_status`, `Occupation`, `Education`, `Why_interest_in_Massage`, `How_did_you_know_about_us`,
`Registration_date`, `Traner_Preference`, `course_of_interest`, `gender`, `username`, `password`, `user_type`) ";
$query .= "VALUES ('','$fname','$address','$sex','$passport','$dob','$mobinput','$homemobinput',
'$email', '$mstatus', '$occupation', '$education', '$wauinmassage','$hduhabttbc',
'', '$tp', '$wmcauin','$sex', '$user_name', '$password', 'S' )";
$register = $connection->query($query);
$customer_id = $connection->query("SELECT customer_id FROM customer WHERE email = '$email' and user_name = '$user_name'")->fetch_object()->customer_id;
$query1 = "INSERT INTO cart ";
$query1 .= "(customer_id) ";
$query1 .= "VALUES ('customer_id')";
$addCart = $connection->query($query1);
if(!$register && !addCart){
echo $query;
}
else
{
$message = 'Registration successfully completed, You can now login';
}
}}?>
This is the html form:
<!-- PopUp registration Form -->
<div id="signup" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- PopUp registration Form content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Massage Course Registration Form</h4>
</div>
<div class="modal-body">
<form method="post" class="form-signin form-group">
<label for="usernameInput" class="usernameinput">Username</label>
<input type="text" class="form-control" id="user_name" name="user_name">
<br>
<label for="passwordinput">Password</label>
<input type="password" class="form-control" id="passwordinput" name="pword">
<br>
<br>
<label for="NameInput">Name</label>
<input type="text" class="form-control" id="InputName" placeholder="Jane Doe" name="fname">
<br>
<label for="ICinput">I.C/Passport No.</label>
<input type="text" class="form-control" id="ICinput" name="passport">
<br>
<label for="EmailInput">Email</label>
<input type="email" class="form-control" id="EmailInput" placeholder="jane.doe#example.com" name="email">
<br>
<label for="mobinput">Mobile No</label>
<input type="number_format" class="form-control" id="mobinput" name="mobinput">
<br>
<label for="homemobinput">Home No</label>
<input type="number_format" class="form-control" id="homemobinput" name="homemobinput">
<br>
<label for="DOBinput">Date of Birth</label>
<input type="date" class="form-control" id="DOBinput" name="dob">
<br>
<label for="SexInput">sex</label>
<select class="form-control" id="SexInput" name="sex">
<option>Male</option>
<option>Female</option>
</select>
<br>
<label for="MaritalStatusInput">Marital Status</label>
<select class="form-control" id="MaritalStatusInput" name="mstatus">
<option>Single</option>
<option>Married</option>
<option>Divorced</option>
<option>Widowed</option>
</select>
<br>
<label for="EducationInput">Education</label>
<input type="text" class="form-control" id="EducationInput" name="education">
<br>
<label for="OccupationInput">Occupation</label>
<input type="text" class="form-control" id="OccupationInput" name="occupation">
<br>
<label for="Addressinput">Address</label>
<input type="text" class="form-control" id="Addressinput" name="address">
<br>
<label for="CourseSelection">Which massage course are you interested in?</label>
<select class="form-control selectpicker" id="CourseSelection" name="wmcauin">
<optgroup label="Professional">
<option>Full Body Massage</option>
<option>Reflexology Course</option>
<option>Aromatherapy Course</option>
</optgroup>
<optgroup label="Advanced">
<option>Pre and Post Natal</option>
<option>Slimming Massage</option>
<option>Lymphatic Drainage</option>
<option>Spa and Facial</option>
<option> Raindrop Techniques</option>
<option>Male Health</option>
<option>Sport Injury</option>
<option>Traditional Malay</option>
</optgroup>
</select>
<br>
<label for="TrainerPreferenceInput">Trainer Preference</label>
<select class="form-control" id="TrainerPreferenceInput" name="tp">
<option>Male Trainer</option>
<option>Female Trainer</option>
</select>
<br>
<label for="InterestFeedbackInput">Why are you interedted in Massage?</label>
<input type="text" class="form-control" id="InterestFeedback" name="wauinmassage">
<br>
<label for="ReferalFeedbackInput">How did you heard about Tim BodyCare Training Centre</label>
<input type="text" class="form-control" id="ReferalFeedbackInput" name="hduhabttbc">
<div class="form-group">
<button type="submit" class="btn btn-primary" name="btn-signup">
<i class="glyphicon glyphicon-open-file"></i> SIGN UP
</button>
</div>
</form>
<div class="modal-footer">
<p>By clicking submit, you agreeing with our terms and conditions</p>
</div>
</div>
</div>
</div>
<!-- End of PopUp registration Form -->
Note that php script and html form all in one file.
Change the variable name in training_index.php
$conn and $connection to $conn
Because in connection.php file you mentioned your db connection variable name as
$con = new mysqli($servername, $username, $password, $dbname);

php- login validations not working

This is my first time validating a form.
I have got stuck on validating the email in theory it seems like it should work but it doesn't.
The following code only works when i remove the email validation:
if ($c_pass1 == $c_pass2) {
} else {
echo "Oops! Your passwords do not match ";
not to sure where i have gone wrong. The validation literally does nothing. is there a better way to validate an email address?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Validates email
if (empty($_POST["email"])) {
$c_emailErr = "You Forgot to Enter Your Email!";
} else {
$c_email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$c_emailErr )) {
$c_emailErr = "You Entered An Invalid Email Format";
}
}
if ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
}
?>
To validate Email Instead Of doing this: if (empty($_POST["email"])) { Try doing this if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false
That should take care of the email part
Now for the password part try this:
if ($_POST[$c_pass1 != $c_pass2]) {echo'wrong password';}else{echo 'good password';}

Forgot password reset not displaying correct email address and not updating password if any error made by user during for submission

I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>

My php is showing validation errors but JS isnt

I am in the early stages of making a registration page for my website. However, the basic form I have created is being validated by javascript and php to ensure the right data will be entered. Even when the javascript is showing no errors and allowing the form to submit, the PHP errors are still being flagged and stopping it. below is the code for the php and html form. Any help will be greatly appreciated, these things are normally a lot easier than anticipated but its driving me crazy as it isnt showing any syntax errors just the errors that i have set up for the user.
The include files just have the mysql password and some basic functions for checking phone numbers.
Thanks in advance
HTML
<?php require_once("functions.inc"); ?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="register.js"></script>
<link rel="stylesheet" href="form.css">
<title>A Form</title>
</head>
<body>
<form id="userForm" method="POST" action="register-process.php">
<div>
<fieldset>
<legend>Registration Information</legend>
<div id="errorDiv">
<?php
if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])){
unset($_SESSION['formAttempt']);
print "errors encountered<br>\n";
foreach ($_SESSION['error'] as $error) {
print $error . "<br>\n";
}//end foreach
} // end if
?>
</div>
<label for="fname">First Name:* </label>
<input type="text" id="fname" name="fname">
<span class="errorFeedback errorSpan" id="fnameError">First Name is required</span>
<br>
<label for="name">Last Name:* </label>
<input type="text" id="lname" name="lname">
<span class="errorFeedback errorSpan" id="lnameError">Last Name is required</span>
<br>
<label for="email">Email Address:* </label>
<input type="text" id="email" name="email">
<span class="errorFeedback errorSpan" id="emailError">Email is required</span>
<br>
<label for="password1">Password:* </label>
<input type="password" id="password1" name="password1">
<span class="errorFeedback errorSpan" id="password1Error">Password is required</span>
<br>
<label for="password2">Varify Password:* </label>
<input type="password" id="password2" name="password2">
<span class="errorFeedback errorSpan" id="password2Error">Password's do not match</span>
<br>
<label for="addr">Address: </label>
<input type="text" id="addr" name="addr">
<br>
<label for="city">City: </label>
<input type="text" id="city" name="city">
<br>
<label for="state">State: </label>
<select name="state" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="FL">Florida</option>
<option value="IL">Illinois</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="WI">Winconsin</option>
</select>
<br>
<label for="zip">ZIP: </label>
<input type="text" id="zip" name="zip">
<br>
<label for="phone">Phone Number: </label>
<input type="text" id="phone" name="phone">
<span class="errorFeedback errorSpan" id="phoneError">Format: xxx-xxx-xxxx</span>
<br>
<br>
<label for="work">Number Type:</label>
<input class="radioButton" type="radio" name="phoneType" id="work" value="work">
<label class="radioButton" for="work">Work</label>
<input class="radioButton" type="radio" name="phoneType" id="home" value="home">
<label class="radioButton" for="home">Home</label>
<span class="errorFeedback errorSpan phoneTypeError" id="phoneTypeError">Please Choose an option.</span>
<br>
<input type="submit" id="submit" name="submit">
</fieldset>
</div>
</form>
</body>
PHP register process.php
<?php
require_once('functions.inc');
//prevent access if they havent submitted the form!!
if (!isset($_POST['submit'])) {
die(header("location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("fname","lname", "email", "password1", "password2");
//check required fields!
foreach ($required as $requiredField) {
if (!isset($_POST[requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (!preg_match('/^[\w .]+$/',$_POST['fname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (!preg_match('/^[\w .]+$/',$_POST['lname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (isset($_POST['state']) && $_POST['state'] != "") {
if (!isValidState($_POST['state'])) {
$_SESSION['error'][] = "Please choose a valid state";
}
}
if (isset($_POST['zip']) && $_POST['zip'] != "") {
if (!isValidZip($_POST['zip'])) {
$_SESSION['error'][] = "ZIP code error";
}
}
if (isset($_POST['phone']) && $_POST['phone'] != "") {
if (!preg_match('/^[\d]+$/', $_POST['phone'])) {
$_SESSION['error'][] = "Phone numbner should be digits only.";
} else if (strlen($_POST['phone']) < 10 ) {
$_SESSION['error'] = "Phone number should be at least 10 digits.";
}
if (!isset($_POST['phoneType']) || $_POST['phoneType'] == "") {
$_SESSION['error'][] = "Please choose a phone type.";
} else {
$validPhoneTypes = array("work","home");
if (!in_array($_POST['phoneType'], $validPhoneTypes)) {
$_SESSION['error'][] = "Please choose a valid phone type";
}
}
}
if (!filter_var($_POST['email'],FILTER_VALIDATE_URL)) {
$_SESSION['error'][] = "Invalid e-mail address!";
}
if ($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'] = "Passwords do not match";
}
//Final Disposition
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
The extension is the rest of the process php file, i have commented where the errors are coming from.... Thanks Again..
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}"); // THIS IS WHERE THE ERROR IS COMNING FROM
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if (isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email already exists";
return false;
}
$lastname = $mysqli->real_escape_string($_POST['lname']);
$firstname = $mysqli->real_escape_string($_POST['fname']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
if (isset($_POST['addr'])) {
$street = $mysqli->real_escape_string($_POST['addr']);
} else {
$street = "";
}
if (isset($_POST['city'])) {
$city = $mysqli->real_escape_string($_POST['city']);
} else {
$city = "";
}
if (isset($_POST['state'])) {
$state = $mysqli->real_escape_string($_POST['state']);
} else {
$state = "";
}
if (isset($_POST['zip'])) {
$zip = $mysqli->real_escape_string($_POST['zip']);
} else {
$zip = "";
}
if (isset($_POST['phone'])) {
$phone = $mysqli->real_escape_string($_POST['phone']);
} else {
$phone = "";
}
if (isset($_POST['phoneType'])) {
$phoneType = $mysqli->real_escape_string($_POST['phoneType']);
} else {
$phoneType = "";
}
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}
}
?>
Your query has a bug in it. Column count isn't the same as value count. You forgot to pass in $state.
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$state}', '{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
error_log("Problem inserting {$mysqli->error}"); // log the error
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}

How to add session to an HTML log in form

I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
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;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420

Categories