PHP form handling with post prints nothing - php

I am trying check if username or email already exists . This is my form
<form role="form" action="kys_SignUp.php" method="post">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I am sending the data in Post Method. My server side script looks like this
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($id,$email,$username,$password);
$stmt->fetch();
if($username == ""){
header("Location : http://localhost/KeyStroke/index.html ");
exit();
}
else{
echo "Username or Email already exists";
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is my kys_DbConnect.php
<?php
$serverName = "localhost";
$username = "jois";
$password = "iluvcoding";
$db_name = "kys_userdata";
$con = new mysqli($serverName,$username,$password,$db_name);
if($con->connect_error){
echo "Connection Error";
}
?>
I don't know why but it print's nothing nor redirects to index.html (index.html exists). How can I figure out what's wrong with my code?

Related

Displaying the full name instead of full name

My login table has Username and Password fields. I want to display the user's full name rather than their username when they logĀ in with their username and password. Instead of saying Welcome USERNAME on the next page, I want to say Welcome FULLNAME.
Here is the index.php or the login page in html:
<form action="" method="POST">
<div class="rows grid">
<div class="row">
<label for="username">User Name</label>
<input type="text" id="username" name="userName" placeholder="Enter Username" required>
</div>
<!--Password-->
<div class="row">
<label for="password">Password</label>
<input type="password" id="password" name="passWord" placeholder="Enter Password" required>
</div>
<!--Submit Button-->
<div class="row">
<input type="submit" id="submitBtn" name="submit" value="Login" required>
<!--Register Link-->
<span class="registerLink">Don't have an account? Register</span>
</div>
</div>
</form>
</div>
</div>
Here is the php:
<?php
// Submit
if(isset($_POST['submit'])){
// Store the names, password, email, number
$userName = $_POST['userName'];
$passWord = $_POST['passWord'];
// Selecting from database
$sql = "SELECT * FROM admin WHERE
usernames = '$userName' AND
passwords = '$passWord'";
// Exceute the query
$result = mysqli_query($conn, $sql);
// Count the number of the account of the same username and password
$count = mysqli_num_rows($result);
// Counts the results into arrys
$row = mysqli_fetch_assoc($result);
// Check if theres account in database
if ($count == 1){
$_SESSION['loginMessage'] = '<span class = "success">Welcome '.$userName.'</span>';
header('location:' .SITEURL. 'dashboard.php');
exit();
}
else{
$_SESSION['noAdmin'] = '<span class = "fail">Please check your username and password and try again.</span>';
header('location:' .SITEURL. 'index.php');
exit();
}
}
?>
Here is the register.php or register link:
<form action="" method="POST">
<div class="rows grid">
<!--Full Name-->
<div class="row">
<label for="fullname">Full Name</label>
<input type="text" id="fullname" name="fullName" placeholder="Enter Full Name" required>
</div>
<!--Username-->
<div class="row">
<label for="username">User Name</label>
<input type="text" id="username" name="userName" placeholder="Enter Username" required>
</div>
<!--Email-->
<div class="row">
<label for="email">Email</label>
<input type="email" id="email" name="emaiL" placeholder="Enter Email" required>
</div>
<!--Mobile Number-->
<div class="row">
<label for="number">Mobile Number</label>
<input type="number" id="number" name="numbeR" placeholder="Enter Mobile Number" required>
</div>
<!--Password-->
<div class="row">
<label for="password">Password</label>
<input type="password" id="password" name="passWord" placeholder="Enter Password" required>
</div>
<!--Submit Button-->
<div class="row">
<input type="submit" id="submitBtn" name="submit" value="Register" required>
<!--Try ko aban aban uni idelete-->
<span class="registerLink">Have an account already? Login</span>
</div>
</div>
</form>
Note: I want to display the input fullname in the welcome dashboard.
Please change your select query to parameterized prepared statement to avoid SQL injection attacks
To display the "fullname", just fetch the db record say into an associative array say $row and use $row["fullname"] (or $row["fullName"] if the field name is actually fullName)
Hence, change the block:
/// other code
$sql = "SELECT * FROM admin WHERE
usernames = '$userName' AND
passwords = '$passWord'";
// Exceute the query
$result = mysqli_query($conn, $sql);
// Count the number of the account of the same username and password
$count = mysqli_num_rows($result);
// Counts the results into arrys
$row = mysqli_fetch_assoc($result);
// Check if theres account in database
if ($count == 1){
$_SESSION['loginMessage'] = '<span class = "success">Welcome '.$userName.'</span>';
header('location:' .SITEURL. 'dashboard.php');
exit();
}
/// other code
to
<?php
/// other code
$sql = "SELECT * FROM admin WHERE usernames = ? AND passwords = ?";
$query = $conn->prepare($sql);
$query->bind_param("ss", $userName,$passWord );
$query->execute();
$result = $query->get_result();
$num = $result->num_rows;
if ($num == 1){
$row = $result->fetch_assoc();
$_SESSION['loginMessage'] = '<span class = "success">Welcome '.$row["fullname"].'</span>';
header('location:' .SITEURL. 'dashboard.php');
exit();
}
/// other code
?>

Allow user to login with a username & password & 4-digit pin code

I want user login with username password and 4 digit pin code and code is in my db. Here is my code sample. If any one here can help me I would very much appreciate it:
<?php
if (isset($_POST['login'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$pincode = $_POST['pincode'];
if (empty($user) OR empty($pincode)) {
echo "<script>alert('Please Fill All Required Field')</script>";
} else {
$select_user = "select * from users WHERE Username = '$user' AND Password ='$pass' pin-code ='?' ";
$run_user_sql = mysqli_query($conn, $select_user);
$check_customer = mysqli_num_rows($run_user_sql);
if ($check_customer ==false) {
echo "<script>alert('Username/Password Wrong')</script>";
exit();
}
if ($check_customer == true) {
$_SESSION['user'] = $user;
echo "<script>alert('You Are Logged In')</script>";
echo "<script>window.open('index.php?dashboard','_self')</script>";
}
}
}
?>
<form action="" method="post">
<div class="form-group">
<div class="form-label-group">
<input type="text" class="form-control" name="user" placeholder="Username" >
<label">Username</label>
</div>
</div>
<div class="form-group">
<div class="form-label-group">
<input type="password" class="form-control" name="pass" placeholder="Password" >
<label >Password</label>
</div>
</div>
<div class="form-group">
<div class="form-label-group">
<input type="text" class="form-control" name="pincode" placeholder="4-Digit Pin Code" >
<label >4-Digit Pin Code</label>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me">
Remember Password
</label>
</div>
</div>
<input type="submit" class="btn btn-primary btn-block" name="login" value="Login">
</form>
Your code seems to be okay, but with a lot of security risks. However, your SQL command is wrong. Change it to the following:
$select_user = "select * from users WHERE Username = '$user' AND Password ='$pass' AND `pin-code` ='{$pincode}'";

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?

login and registration in php wrong redirection

register form css and html
<div class="col-md-12">
<div class="box">
<div class="box-header">
<center>
<h2>Register A New Account</h2>
</center>
</div>
<!-- box-header ends -->
<form action="signup.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label>FIRST NAME</label> <input class="form-control" name="first" required="" type="text">
</div>
<!--form group -->
<div class="form-group">
<label>LAST NAME</label> <input class="form-control" name="last" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>Email</label> <input class="form-control" name="email" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>USER NAME</label> <input class="form-control" name="uid" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>PASSWORD</label> <input class="form-control" id="pwd" name="pwd" onchange="validatePassword()" required="" type="password">
</div>
<!-- form group -->
<div class="form-group">
<label>CONFIRM PASSWORD</label> <input class="form-control" id="cpwd" name="cpwd" required="" type="password">
</div>
<!-- form group -->
<div class="form-group">
<label>COUNTRY</label> <input class="form-control" name="country" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>CITY</label> <input class="form-control" name="city" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>ADDRESS</label> <input class="form-control" name="address" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>CONTACT</label> <input class="form-control" name="phone" required="" type="text">
</div>
<!-- form group -->
<div class="form-group">
<label>PROFILE PICTURE</label> <input class="form-control" name="image" required="" type="file">
</div>
<!-- form group -->
<div class="text-center">
<button class="btn btn-primary" name="submit" type="submit"><i class="fa fa-user-md" style="padding:0px 5px;"></i>Sign Up</button>
</div>
<!-- text-center -->
</form>
<!-- form ends -->
</div>
<!-- box ends -->
</div>
<!-- col-m-9 ends -->
php code to enter into database and validate
<?php
use PHPMailer\PHPMailer\PHPMailer;
if (isset($_POST['submit'])) {
include_once 'includes/db.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$img = mysqli_real_escape_string($conn, $_FILES['image']['name']);
$temp_name = mysqli_real_escape_string($conn, $_FILES['image']['tmp_name']);
$userip = getUserIP();
move_uploaded_file($temp_name, "customer/customer_images/$img");
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd) || empty($country) || empty($city) || empty($phone) || empty($address) || empty($img)) {
echo "<script>alert('Empty Fields.Please fill all the details');
window.location.href='../signup.php?signup=empty';
</script>";
exit();
} else {
//check if input character are valid
if (!preg_match("/^[a-zA-z]*$/", $first) || !preg_match("/^[a-zA-z]*$/", $last)) {
echo "<script>alert('Invalid Characters');
window.location.href='../signup.php?signup=invalid';
</script>";
exit();
} else {
//check valid email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('Ivalid email id');
window.location.href='../signup.php?signup=email';
</script>";
exit();
} else {
//check if username is same as others'
$sql = "SELECT * FROM users WHERE user_uid='$uid' AND user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<script>alert('email or username already exist.Please try again with new email id');
window.location.href='../signup.php?signup=userexist';
</script>";
exit();
} else {
//Hash the password
$hashedpwd = password_hash($pwd, PASSWORD_BCRYPT);
$token = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789!##$%^&*()';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$sel_cart = "select * from cart where ip_add='$user_ip'";
$run_cart = mysqli_query($conn, $sel_cart);
$cart_check = mysqli_num_rows($run_cart);
//Insert user into database
$sql = "INSERT INTO users (user_first,user_last,user_email,user_uid,user_pwd,isEmailConfirmed,token,country,city,address,phone,image,userip) VALUES('$first','$last','$email','$uid','$hashedpwd','0','$token','$country','$city','$address','$phone','$img','$userip');";
mysqli_query($conn, $sql);
if ($cart_check > 0) {
$_SESSION['user_email'] = $email;
echo "<script>alert('Registration successfull.Please check your mail to verfiy the details.Thank you');
window.open('checkout.php','_self');
</script>";
} else {
$_SESSION['user_email'] = $email;
echo "<script>alert('Registration successfull.Please check your mail to verfiy the details.Thank you');
window.location.href='../signup.php?signup=successfull';
window.open('index.php','_self');
</script>";
}
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Guys this my code for registration. The problem here is that when a user who is not registered and adds a product into his cart goes to registration page. After signing up he needs to go the checkout page . If there are no items inside the cart then the page needs to redirected to index.php . The issue i face is the data gets entered into database when the cart has one item and then after registering it redirects to index.php rather than checkout.php .
There is small variable name mistake in
$sel_cart = "select * from cart where ip_add='$user_ip'";
You have added $user_ip instead of $userip. update your code by following,
$sel_cart = "select * from cart where ip_add='$userip'";

While clicking submit i get an error but its still inserting data in the database

I made a form and when i don't fill in the form i get an error just how i wanted.
Example of the error i made:
Error if you dont fill in anything
error if you fill in capital letters
so now if you press enter you need to get a error. Its giving me the error but then its inserting empty data which is wrong, it should not insert data at all.
THIS IS MY CODE:
<?php
// Connecting to database
require('config.php');
if (isset($_POST['companyname']) && isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['email']) && isset($_POST['function']) && isset($_POST['password'])) {
// Values to insert
$companyname = mysqli_real_escape_string($con, $_POST['companyname']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$surname = mysqli_real_escape_string($con, $_POST['surname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$function = mysqli_real_escape_string($con, $_POST['function']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$companyname_error = "";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// empty
if (empty($_POST['companyname'])) {
$companyname_error = "companyname is required!";
} else {
$companyname = test_input($_POST["companyname"]);
//check characters validation
if (!preg_match("/^[^A-Z]+$/", $companyname)) {
$companyname_error = "Only use small letters and white spaces!";
}
}
}
// voer insert uit
$sql = $con->prepare("INSERT INTO company (companyname) VALUES (?)");
$sql->bind_param('s', $companyname);
$sql->execute();
//RESULT
$result = $sql->get_result();
// id
$companyId = mysqli_insert_id($con);
//insert INTO
$sql = $con->prepare("INSERT INTO employee (name, surname, email, function, password, companyid) VALUES (?, ?, ?, ?, ?, ?)");
$sql->bind_param('ssssss', $name, $surname, $email, $function, $password, $companyId);
$sql->execute();
$result = $sql->get_result();
}
?>
HTML form:
<form class="form_register_page" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label class="register_headers">full name</label> <input class="form-control" id="name" name="name" placeholder="Enter your full name" type="text">
</div>
<div class="form-group">
<label class="register_headers">Full last name</label> <input class="form-control" id="lastname" name="surname" placeholder="Enter your last name" type="text">
</div>
<div class="form-group">
<label class="register_headers">company name</label> <input class="form-control" id="company" name="companyname" placeholder="Enter your company" type="text">
<span class="error">* <?php echo $companyname_error;?></span>
</div>
<div class="form-group">
<label class="register_headers">function</label> <input class="form-control" id="function" name="function" placeholder="Enter your function" type="text">
</div>
<div class="form-group">
<label class="register_headers">E-Mail adress</label> <input class="form-control" id="email" name="email" placeholder="Enter your E-Mail adress" type="text">
</div>
<div class="form-group">
<label class="register_headers">Password</label> <input class="form-control" id="password" name="password" placeholder="Enter your password" type="password">
</div>
<div class="form-group">
<div class="form-check">
<label class="form-check-label"><input class="form-check-input" type="checkbox"> I agree all statements in <b>terms of service</b></label>
</div>
</div><button class="click_more" type="submit">Register</button>
<span class="error">
<?php
echo $companyname_error;
?>
</span>
</form>
Your $sql->execute() statements are always run because they are completely outside the code blocks which tests for the error conditions and there is no separate test for the errors having being raised. If you put the inserts inside a test for $companyname_error being empty you won't get the inserts. eg
if (empty($comanyname_error))
{
do your inserts here
}

Categories