Form submission to database errors if empty fields [duplicate] - php

This question already has answers here:
500 internal server error, how to debug [duplicate]
(2 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I have a form that submits business information. We dont always have all the info so I want to have it so that only the Business Name and Contact are required. The issue I have now is if the email is empty the page errors out. Give me a 500 error. I am using the !emtpy and trim in the script.
add/index.php
session_start();
if (!isset($_SESSION['logged_in'])) {
header('Location:https://portal.site.net/');
}
require 'dbconnect.php';
if(isset($_POST['addsmb'])){
$businessName = !empty($_POST['businessName']) ? trim($_POST['businessName']) : null;
$contactName = !empty($_POST['contactName']) ? trim($_POST['contactName']) : null;
$title = !empty($_POST['title']) ? trim($_POST['title']) : null;
$phone = !empty($_POST['phone']) ? trim($_POST['phone']) : null;
$email = !empty($_POST['email']) ? trim($_POST['email']) : null;
$url = !empty($_POST['url']) ? trim($_POST['url']) : null;
$city = !empty($_POST['city']) ? trim($_POST['city']) : null;
$state = !empty($_POST['state']) ? trim($_POST['state']) : null;
$outletid = !empty($_POST['outletid']) ? trim($_POST['outletid']) : null;
$user = !empty($_POST['user']) ? trim($_POST['user']) : null;
$sql = "SELECT COUNT(Phone) AS num FROM smb_leads WHERE Phone = :phone";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':phone', $phone);
//.
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
$_SESSION['error'] = "1";
header("Location: ../error.php".$qstring);
exit;
}
if(empty($_POST['email'])){
$email = "No Email";
}
$sql = "INSERT INTO smb_leads (Outlet_ID, URL, State, City, DUNS_Name, Contact_Name, Title, Phone, created_by, email) VALUES (:outletid, :url, :state, :city, :businessName, :contactName, :title, :phone, :user, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':businessName', $businessName);
$stmt->bindValue(':contactName', $contactName);
$stmt->bindValue(':title', $title);
$stmt->bindValue(':phone', $phone);
$stmt->bindValue(':url', $url);
$stmt->bindValue(':city', $city);
$stmt->bindValue(':state', $state);
$stmt->bindValue(':outletid', $outletid);
$stmt->bindValue(':user', $user);
$stmt->bindValue(':email', $email);
$result = $stmt->execute();
}
// Redirect to the listing page
header("Location: ../index.php".$qstring);
form
<form action="add/index.php" method="post">
<span style="color: gray; font-size: 12px;" >Fields marked with a * are required </span>
<div class="form-row">
<div class=".form-group.required col-md-4">
<input type="text" class="form-control" id="businessName" name="businessName" placeholder="* Business Name">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" id="contactName" name="contactName" placeholder="* Contact Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control" id="title" name="title" placeholder="Contact Title">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" id="phone" name="phone" placeholder="* Contact Phone #">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" id="url" name="url" placeholder="Company Website">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control" id="city" name="city" placeholder="City">
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control" id="state" name="state" placeholder="State">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control" id="outletid" name="outletid" placeholder="Outlet ID" value="<?php echo $_SESSION['outlet_id']; ?>">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" id="user" name="user" placeholder="* Your Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-1">
</div>
<button type="submit" name="addsmb" value="Register" class="btn btn-primary">Submit</button>
</form>
Im guessing my error is somewhere in here.
$phone = !empty($_POST['phone']) ? trim($_POST['phone']) : null;
$email = !empty($_POST['email']) ? trim($_POST['email']) : null;
The script works just fine if i leave everything else blank but the name, business and email.
My Error
This page isn’t working portal.site.net is currently unable to handle this request.
HTTP ERROR 500

Related

How can i get my registration form page to work with php?

please i'm kinda new to website development. i tried to create a registration page to work with my database but my registration form page is not responding to the php coding page.
please i need your assistance. thank
This is my registration.html page
i don't know if the error is from my registration form page
<form action="student.php" name="register" id="register" method="POST" data-aos="fade">
<div class="form-group row">
<div class="col-md-6 mb-3 mb-lg-0">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First name" required>
</div>
<div class="col-md-6">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last name" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="studentid" id="studentid" class="form-control" placeholder="Student ID" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="level" class="form-control" placeholder="Level" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<p class="mb-0">Gender</p>
<input name="gender" type="radio" value="m" required> Male
<input name="gender" type="radio" value="f" required> Female
</div>
</div>
<div class="form-group row">
<div id="date-picker" class="col-md-12 md-form md-outline input-with-post-icon datepicker" inline="true">
<input type="text" name="dob" class="form-control" id="date9" placeholder="DD/MM/YYYY" required>
<i class="fas fa-calendar input-prefix"></i>
</div>
</div>
<script>
$('.datepicker').datepicker({
inline: true;
});
</script>
<div class="form-group row">
<div class="col-md-12">
<input type="email" name="email" class="form-control" placeholder="Email" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="phone" name="phonenumber" id="phonenumber" class="form-control" placeholder="+234 8179 5523 71" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="department" name="department" class="form-control" placeholder="Department" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="password" value="" id="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="confirmpassword" id="confirmpassword" value="" class="form-control" placeholder="Confirm Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<input type="submit" name="submit" class="btn btn-primary py-3 px-5 btn-block btn-pill" value="SUBMIT">
</div>
</div>
</form>
This is my Php page for the form
or maybe the error is from my php code. please help detect the problem guys. Thanks.
<?php
session_start();
// initializing variables
$studentid = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'oneschool');
// REGISTER USER
if (isset($_POST['submit'])) {
// receive all input values from the form
$firstname = mysqli_real_escape_string($db, $_POST['firstname']);
$lastname = mysqli_real_escape_string($db, $_POST['lastname']);
$studentid = mysqli_real_escape_string($db, $_POST['studentid']);
$level = mysqli_real_escape_string($db, $_POST['level']);
$gender = mysqli_real_escape_string($db, $_POST['gender']);
$dob = mysqli_real_escape_string($db, $_POST['dob']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$phonenumber = mysqli_real_escape_string($db, $_POST['phonenumber']);
$department = mysqli_real_escape_string($db, $_POST['department']);
$password_1 = mysqli_real_escape_string($db, $_POST['password']);
$password_2 = mysqli_real_escape_string($db, $_POST['confirmpassword']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($studentid)) { array_push($errors, "Student ID is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM student_registra WHERE studentid='$studentid' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query) or die(mysqli_error($db));
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['studentid'] === $studentid & $user['email'] === $email) {
array_push($errors, "Student Id already taken");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
$_SESSION['success'] = "Registration Sucessful";
header('location: index.html');
}
}
i don't know what seems to be the problem, because i run it the first time it worked, but when i shutdown my laptop and turn it on back again after my lunch, it stop working.
Instead of it to read the .php code it's rather displaying the whole .php code and i've checked the code, i can't find what seems to be the problem.
please guys, i'll need your help in fixing this or detecting the problem.
thanks
EDIT, You have a lot of useless codes that make your code so slow, Like $_SESSION['success']; This is not neccessary, Change your index.html to index.php and delete it because it do nothing, You can check session by student id You have two gender Inputs, how comes you assign one of them? This is first mistake
Secondly, Use Prepared Statements to avoid SQLI Attacks
Thirdly How comes you header a html page when you're in php page? change index.html to index.php
And Use this code instead:
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$prepared = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
$query = $prepared;
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
# Change your files index.html To index.php
header('location: index.php');
}

View and update value from database in `<input>` using PHP

I have an update form that has three inputs. Now, I want to retrieve values from database in the inputs and update them after I click update and it works fine. But, the problem is that I must refresh after pressing the update button to see the changes (the automatic refresh and manual refresh). I need the value to change instantly after pressing the update button. How to do this? This is my code:
<?php
require_once 'core/init.php';
$result = $db->query("SELECT * FROM customers WHERE id = '$customer_id'");
while($res = mysqli_fetch_assoc($result)) {
$first_name = $res['first_name'];
$last_name = $res['last_name'];
$mobile_number = $res['mobile_number'];
}
if(isset($_POST['submit_0'])) {
$first_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$db->query("UPDATE customers SET first_name = '{$first_Name}', last_Name = '{$last_Name}' WHERE id = '{$customer_id}'");
}
?>
<form action="personal_details.php" method="post" id="personal_details">
<div class="row">
<div class="form-group col-lg-12">
<label for="First_Name" style="font-weight: bold; cursor:text;"><span style="color:red;">* </span>First Name</label>
<input type="text" name="First_Name" id="First_Name" class="form-control form-control-lg"
value="<?=$first_name;?>" style="width:770px; background-color:#EEEEEE;">
</div>
</div>
<div class="row">
<div class="form-group col-lg-12">
<label for="Last_Name" style="font-weight: bold; cursor:text;"><span style="color:red;">* </span>Last Name</label>
<input type="text" name="Last_Name" id="Last_Name" class="form-control form-control-lg"
value="<?=$last_name;?>" style="width:770px; background-color:#EEEEEE;">
</div>
</div>
<div class="row">
<div class="form-group col-lg-7">
<label for="mobile_number" style="font-weight: bold;"><span style="color:red;">* </span>Mobile Phone Number</label>
<input type="tel" name="mobile_number" id="monu" class="form-control form-control-lg"
value="<?=$mobile_number;?>" style="background-color:#EEEEEE; cursor:default;" readonly>
</div>
</div>

Modal doesn't validate with PHP

Modal will not trigger my PHP validation.
I can't get my modal to use my PHP validation. HTML validation works. It connects to the DB and makes the updates, but skips the server-side validation. I would appreciate any help, this is new to me why a modal won't validate.
My PHP and Modal form is in one file. I know I need more error messages added to my form, but leaving the phone number and first name out triggers no error messages, so I will add more once I fix this issue. The code just executes and changes the DB.
<?php
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
session_start();
// Include db config
require_once 'includes/dbh.inc.php';
// Process form when post submit
// if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Sanitize POST
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$error=array();
// $error = false;
// $error = isset($_SESSION['error']);
// $error = $_SESSION['error'];
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$first = test_input($_POST['first']);
$last = test_input($_POST['last']);
$email = test_input($_POST['email']);
$unit = $_SESSION['unit'];
$bed = test_input($_POST['bed']);
$bath = test_input($_POST['bath']);
$web = test_input($_POST['web']);
$phone = test_input($_POST['phone']);
$manage = test_input($_POST['manage']);
$ck = $_POST['rent'];
$id = $_SESSION['id'];
// Validate name
if(empty($first) || empty($last)){
$error['name'] = "Enter name";
}
// Validate email
if(empty($email)){
$error['email'] = "Please enter email";
}
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['email'] = "Invalid email format";
}
// Validate name
if(empty($bed) || empty($bath)){
$error['rooms'] = 'Please enter bed/bath #';
}
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$web)) {
$error['web'] = "Invalid URL";
}
// Validate name
if(empty($phone)){
$error['phone'] = 'Please enter your phone';
}
//Check phone # format 000-000-0000
if(!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
$error['phone'] = 'Please enter correct phone format';
}
//Check manage format
if (!preg_match("/^(\s\(([^)]+)\))?[[:punct:]]?\p{Lu}+(?:[\s'-]?[\p{L}\d]+)+(\(([^)]+)\))*$/", $manage)) {
$error['manage'] = 'Please enter correct management format';
}
if (empty($error)) {
var_dump($error);
print_r($error);
$sql = 'UPDATE condos_hp SET user_firstname=:first, user_lastname=:last, user_email=:email, user_bed=:bed, user_bath=:bath, user_web=:web, user_phone=:phone, user_manage=:manage, rent=:rent WHERE id=:id';
// Prepare statement
$stmt = $pdo->prepare($sql);
// Bind params
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':unit', $unit);
$stmt->bindParam(':bed', $bed, PDO::PARAM_INT);
$stmt->bindParam(':bath', $bath, PDO::PARAM_INT);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_INT);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute(array(':first'=>$first, ':last'=>$last, ':email'=>$email, ':bed'=>$bed, ':bath'=>$bath, ':web'=>$web, ':phone'=>$phone, ':manage'=>$manage, ':rent'=>$ck, ':id'=>$id));
// if($stmt){
// header('Location: index1.php');
//}
if (isset($_POST['update'])) {
// session_start();
//Then delete all SESSION variables
session_unset();
//And destroy the current session that is running
session_destroy();
// exit(header("Location: http://www.harbour-place.com/login0.php?update=success"));
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=http://www.harbour-place.com/login0.php>");
}
else{
exit(header("Location: http://www.harbour-place.com/login0.php?update=success"));
}
}
}
include_once 'includes/mailer2.php';
?>
<!-- Button trigger modal -->
<div class="row justify-content-center">
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#exampleModalCenter">
UPDATE
</button>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="userupdateform" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">UPDATE RENTAL UNIT # <?php echo htmlentities($_SESSION['unit']) ?> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label >First Name</label>
<input type="text" class="form-control form-control-sm <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>" name="first" value="<?php echo htmlentities($_SESSION['first']) ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
<div class="form-group col-md-4">
<label >Last Name</label>
<input type="text" class="form-control form-control-sm" name="last" value=<?php echo htmlentities($_SESSION['last']) ?> required>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-8">
<label >Email</label>
<input type="text" class="form-control form-control-sm" name="email" value=<?php echo htmlentities($_SESSION['email']) ?> required>
</div>
<!--<div class="form-group col-md-4">
<label >Unit</label>
<input type="text" class="form-control form-control-sm" name="unit" value=<php echo $_SESSION['u_unit'] ?> required>
</div>-->
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-2">
<label >Bed</label>
<input type="text" class="form-control form-control-sm" name="bed" value=<?php echo htmlentities($_SESSION['bed']) ?> required>
</div>
<div class="form-group col-md-2">
<label >Bath</label>
<input type="text" class="form-control form-control-sm" name="bath" value=<?php echo htmlentities($_SESSION['bath']) ?> required>
</div>
<div class="form-group col-md-4">
<label >Web Site - www.myunit.com</label>
<input type="text" class="form-control form-control-sm" name="web" value=<?php echo htmlentities($_SESSION['web']) ?> required>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-3">
<label >Phone 000-000-0000</label>
<input type="text" id="yourphone2" class="form-control form-control-sm <?php echo (!empty($error['phone'])) ? 'is-invalid' : ''; ?>" name="phone" value="<?php echo htmlentities($_SESSION['phone']) ?>">
<span class="invalid-feedback"><?php echo $error['phone']; ?></span>
</div>
<div class="form-group col-md-5">
<label >Managment Co (VRBO, Self,etc)</label>
<input type="text-capitalize" class="form-control form-control-sm" name="manage" value="<?php echo htmlentities( $_SESSION['manage']) ?>" required>
</div> </div>
<!--<div class="form-row justify-content-center">
<div class="form-group col-md-8">
<label >Managment Co - VRBO etc.</label>
<input type="text" class="form-control form-control-sm" name="manage" value="" required>
</div></div>-->
<div class="form-row justify-content-center">
<div class="custom-control custom-checkbox">
<input type="hidden" name="rent" value="0">
<input type="checkbox" value="1" name="rent" class="custom-control-input" id="customCheck1" checked="checked">
<label class="custom-control-label" for="customCheck1">Check to show on the rental site</label>
</div></div>
<p class="text-center mb-1"><small><i class="fas fa-lock"></i>Your Information is Safe With us!<br> You will need to re-login after clicking Update<br>This also updates the HP rental website listing. </small></p>
<button type="submit" class="btn btn-primary btn-sm" name="update">UPDATE HP UNIT</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
There are a couple issues here
You are setting $error to a boolean value, trying to define an array key with a value on a boolean doesn't work, it will continue to just be a boolean [Edit] if the value of $error evaluates to false before assigning array key => values to it, it will convert to an array but if it evaluates to true it will result in Warning: Cannot use a scalar value as an array and continue to be a boolean
You are never checking $error to stop the script from executing and updating the database

inserting a blank row before inserting the correct one mysql

I am working on a angular5 / php backend project, and I am having an issue where I have a registration form, when the user registers it creates a blank row (empty strings values) in the user table followed by the correct row (colomn values).
The following is my form:
<form *ngIf="!isLogin" (submit)="onRegisterSubmit()" [formGroup]="registerForm">
<div class="form-control">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname" formControlName="fn">
<div class="throw_error" *ngIf="registerForm.controls.fn.invalid && registerForm.controls.fn.touched">
<div *ngIf="registerForm.controls.fn.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.fn.errors?.minlength">This field must be at least 3 characters</div>
<div *ngIf="registerForm.controls.fn.errors?.maxlength">This field must have at most 10 characters</div>
</div>
</div>
<div class="form-control">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname" formControlName="ln">
<div class="throw_error" *ngIf="registerForm.controls.ln.invalid && registerForm.controls.ln.touched">
<div *ngIf="registerForm.controls.ln.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.ln.errors?.minlength">This field must be at least 3 characters</div>
<div *ngIf="registerForm.controls.ln.errors?.maxlength">This field must have at most 10 characters</div>
</div>
</div>
<div class="form-control">
<input type="email" name="email2" id="email2" class="form-control" placeholder="Email Address" formControlName="email2">
<div class="throw_error" *ngIf="registerForm.controls.email2.invalid && registerForm.controls.email2.touched">
<div *ngIf="registerForm.controls.email2.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.email2.errors?.email && !registerForm.controls.email2.errors?.required">This email is invalid</div>
</div>
</div>
<div class="form-control">
<input type="password" name="password2" id="password2" class="form-control" placeholder="Password" formControlName="password2">
<div class="throw_error" *ngIf="registerForm.controls.password2.invalid && registerForm.controls.password2.touched">
<div *ngIf="registerForm.controls.password2.errors?.required">This field is required</div>
<div *ngIf="registerForm.controls.password2.errors?.minlength">This field must be at least 6 characters</div>
<div *ngIf="registerForm.controls.password2.errors?.maxlength">This field must have at most 15 characters</div>
</div>
</div>
<div class="form-control">
<input type="password" name="confirmPassword" id="confirm-password" class="form-control" placeholder="Confirm Password" formControlName="confPass">
<div class="throw_error" *ngIf="registerForm.controls.confPass.touched && registerForm.controls.confPass.errors?.MatchPassword">Passwords do not match</div>
</div>
<div class="form-control">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<input type="submit" name="register-submit" id="register-submit" [disabled]="registerForm.invalid"
class="form-control btn btn-register" value="Submit">
<span class="throw_error" id="success">{{resultReg}}</span>
</div>
<div class="col-sm-3"></div>
</div>
</div>
</form>
This is my typescript code for the registration function:
onRegisterSubmit() {
const regFormValue = this.registerForm.value;
this.http.post("http://localhost/ProjetErgonomie/RegUser.php", regFormValue)
.subscribe(data => {
this.receivedData = data;
if (this.receivedData.success) {
this.resultReg = "User added successfully";
} else {
this.resultReg = this.receivedData.errors;
}
}, (error) => {
console.log(error);
});
}
And this is my RegUser.php page:
<?php
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Origin: *");
require_once ('./DBConnect.php');
$conn = mysqli_connect($servername, $username, $password, $db ,$port);
$regUserData = json_decode(file_get_contents("php://input"),true);
$fn = $regUserData['fn'];
$ln = $regUserData['ln'];
$email = $regUserData['email2'];
$pass = $regUserData['password2'];
$confPass = $regUserData['confPass'];
$errorsReg = "";
$dataReg=array();
if($fn === '' || $ln === '' || $email === '' || $pass === '' || $confPass === ''){
$errorsReg = 'Please fill all fields';
$dataReg['success'] = FALSE;
}
else{
$checkUserQuery = "select * from user where Email = '".$email."'";
$result = $conn->query($checkUserQuery);
if(mysqli_num_rows($result)>0){
$errorsReg = 'User already exists';
$dataReg['success'] = FALSE;
}
else{
$sql = "INSERT INTO user (Firstname, Lastname, Email, Password, NewUser)
VALUES ('".$fn."','".$ln."','".$email."','".md5($pass)."',1)";
mysqli_query($conn,$sql);
$dataReg['success'] = TRUE;
}
}
$dataReg['errors']=$errorsReg;
echo json_encode($dataReg);
can you please tell me why am I getting a blank row before having the correct row inserted?

Get email id on another page

After submit in signup page my signUp page redirects to info.php where I want to collect additional info of user using email id he gives on signup page but when I tried to get the email id of user through sessions, session return empty value.
THIS IS MY SIGNUP CODE
<?php
session_start();
if(isset($_POST['submit'])){
$name= $_POST['_user'];
$email = $_POST['_email'];
$pass = $_POST['_password'];
//Insert Data
$sql = "INSERT INTO signup(name,email,password)
VALUES('$name','$email','$pass')";
//Data Validation
if(mysqli_query($conn,$sql)){
echo "<script>alert('SignUp Successfull')</script>";
$_SESSION['user_email'] = $email;
header('Location: info.php');
}
else{
echo "<script>window.alert('You are already a user.')</script>";
}
}
mysqli_close($conn);
?>
AND THIS MY INFO.PHP CODE
<?php
session_start();
if(isset($_POST['_submit'])){
if(empty($_POST['_address']) || empty($_POST['_country']) || empty($_POST['_number']) || empty($_POST['_cnic']) || empty($_POST['_passport'])){
echo "<script>window.alert('All fields are required')</script>";
}
else{
$address = $_POST['_address'];
$country = $_POST['_country'];
$number = $_POST['_number'];
$cnic = $_POST['_cnic'];
$passport = $_POST['_passport'];
$email=$_SESSION['user_email'];
$query = "INSERT INTO info(email,address,country,mobile,cnic,passport)
VALUES('$email','$address','$country','$number','$cnic','$passport')";
if(mysqli_query($conn,$query)){
header('Location: ../index.php');
}
else{
echo "<script>window.alert('Error While Entering the data!.')</script>";
}
}
}
mysqli_close($conn);
?>
In addition I use this global session variable for login page and it works fine.
UPDATE
SIGNUP HTML CODE
<div class="outside">
<form class="form-horizontal" role="form" method="post">
<div class="form-group">
<label class="control-label col-sm-3 glyphicon glyphicon-user" for="name"></label>
<div class="control-label col-sm-8">
<input type="text" name="_user" class="form-control" id="name" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="email">
<img class="glyphicon1" src="../assests/at-sign.png">
</label>
<div class="control-label col-sm-8">
<input type="email" name="_email" class="form-control" id="email" placeholder="Enter Email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3 glyphicon glyphicon-lock" for="password"></label>
<div class="control-label col-sm-8">
<input type="password" name="_password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button name="submit" id="submit" value="Upload" type="submit" class="btn btn-default">Confirm SignUp</button>
</div>
</div>
<p>Already a User? LogIn</p>
</form>
</div>
Use this for Returns the auto generated id used in the last query
mysqli_insert_id($link)

Categories