my code generating fetal error in the code it check all fields except cnic filed, a cnic already exist in table in multiple rows.When we try to create login for new member with same cnic it create duplicate entry rather to checking and generate error for the already exiting cnic. i mean to say it check both email and cnic if both exit it deny for new registration but in my case some time it check and some time it not check the email and cnic. Please correct my code i try a lot but i am unable to filed where i'm doing wrong.Your help in this regard will highly helpful for me and i will be highly thankful to you.
<?php
//Start the Session
require_once("config.php");
//error_reporting(0);
$headers ='';
$res = '';
$Message = '';
$Message1 = '';
$Message2 = '';
$recaptcha = '';
$query ="SELECT * FROM tbl_signup;";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$user_cnic = $row['apli_cnic'];
$User_Email = $row['apli_email'];
if(isset($_POST['ButtonSignUp']))
{
$Cnic=mysqli_real_escape_string($conn, $_POST['cnic']);
$Name= mysqli_real_escape_string($conn,$_POST['namesurname']);
$Email = mysqli_real_escape_string($conn, $_POST['email']);
$Password = mysqli_real_escape_string($conn, $_POST ['password']);
$CnfrmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
$ActivationCode = md5( rand(0,1000) );
$Status = 0;
if ($Cnic == $user_cnic)
{
$Message = "Sign Up Failed. Account With CNIC: $user_cnic Already Exist";
}
elseif($Email == $User_Email)
{
$Message1 = "$Email Already Exist. Please Enter Another Email Address.";
}
elseif($Password != $CnfrmPassword)
{
$Message2 = "Your Password does not match the Confirm Password";
}
elseif ($Password == $CnfrmPassword)
{
$sql= "INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');";
mkdir("DocumentUpload/$Cnic");
$to_email = $Email;
$subject = 'Verify Your Email';
$message = "Your account information is successfully updated. Please click the following link For verifying and activate your account.
$headers = 'From: abc.com
$res = mysqli_query($conn, $sql);
if(mail($to_email, $subject, $message, $headers))
{
}
}
if($res == 1)
{
header("location:VerifyEmailWait.php");
}
else
{
}
}
mysqli_close($conn);
?>
<form id="sign_up" method="POST">
<input type="number" class="form-control" name="cnic" placeholder="CNIC e.g. 3520212345678" maxlength="13" required autofocus autocomplete="off">
<input type="text" class="form-control" name="namesurname" placeholder="Full Name (As Per CNIC)" required autofocus autocomplete="off">
<input type="email" class="form-control" name="email" placeholder="Email Address" required autocomplete="off">
<input type="password" class="form-control" name="password" id="password" minlength="8" placeholder="Password" required autocomplete="off">
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" minlength="8" placeholder="Confirm Password" required autocomplete="off">
<button class="btn btn-block btn-lg bg-pink waves-effect" type="submit" name="ButtonSignUp">SIGN UP</button>
Already a Member? Please Sign In
</form>
Your insert statement
INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
is wrong it must be
INSERT INTO tbl_signup(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
Where you use the proper tabke name a generic table like you did is not allowed.
But please read this about passwords
And of course that about preventing sql injection
Before you proceed in your development.
Related
I created a registration form using HTML, created a database called “web_app_dev" and linked the form to the database using PHP, however, when I test the form and click the Submit button nothing happens. It doesn't show me any errors and the information does not get posted into the database.
The table in the database is called "registration"
Below is the code for the "registerform.php"
<?php
session_start();
$FirstName = "";
$LastName = "";
$gender = "";
$email = "";
$password = "";
$errors = array();
// connect to database
$conn = mysqli_connect('localhost', 'root', '', 'web_app_dev');
// check if the registration button is clicked
if (isset($_POST['reg_btn'])) {
// Receive information from the form
$FirstName = mysqli_real_escape_string($conn, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($conn, $_POST['LastName']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// make sure that the form is correctly filled
if (empty($FirstName)) {
array_push($errors, "First Name is required");
}
if (empty($LastName)) {
array_push($errors, "Last Name is required");
}
if (empty($gender)) {
array_push($errors, "Gender is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
//check if user already exists in the database
$user_check = "SELECT * FROM registration WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $user_check);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($email['email'] == $email) {
array_push($errors, "A user with this email already exists");
}
}
//register the user if there are no errors
if (count($errors) == 0) {
$password = md5($password); //encrypt the password before saving it into the database
$query = "INSERT INTO registration (FirstName, LastName, gender, email, password)
VALUES('$FirstName', '$LastName', '$gender', '$email', '$password')";
mysqli_query($conn, $query);
$_SESSION['success'] = "Registration successful!";
}
}
?>
Below is the code from the html file that contains the html code for the form, the file's name is "regform.php"
<?php include('registerform.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" href="edits.css">
</head>
<body>
<style>
body {
background-image: url("img/bg2.jpg");
}
</style>
<div class="header">
<h2 style="margin-right: 60px;">Register</h2>
</div>
<form method="post" action="registerform.php">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName"
placeholder="Enter First Name..."/>
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName"
placeholder="Enter Last Name..."/>
</div>
<div class="radio-group">
<label for="m"><input type="radio" name="gender"
value="m">Male</label>
<label for="f"><input type="radio" name="gender"
value="f">Female</label>
</div>
<div class="input-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Enter
Email...">
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="text" name="password" id="password"
placeholder="Enter password...">
</div>
<div class="input-group">
<button type="submit" class="btn" id= "reg_btn"
name="reg_btn" value="reg_btn">Submit</button>
</div>
</form>
</body>
</html>
[Edit] Bellow is a screenshot of the error message that shows, after adding the error reporting code before the mysqli_connect() code.
Error message after filling in the form and clicking the register button
"Line 59" from the error message, is referring to the second last line from the registerform.php code. the code on that line is;
mysqli_query($conn, $query);
The data I put in the form is also shown bellow
Data inserted in the form
It's because you're inserting a hash of the password into the database, not the original password the user entered. md5 hashes usually come out at 32 characters (regardless of the length of the hashed data).
Note that - as you were warned above - md5 is obsolete now and insecure, it can be cracked easily. So should switch to using php's secure password_hash function. As per its documentation you need to allow at least 60 characters for storing a hash created by that function (but it advises 255 is better)
i have a registration form where it has a password field and a confirm password field. I would like the password and confirm password fields to be the same so it can register the new users information.
form:
<form class="form-signin" name="Register_Form" method="post" action="regcheck.php">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="inputPassword" class="form-control" placeholder="Password" required>
<label for="CPassword" class="sr-only">Confirm Password</label>
<input type="password" id="CPassword" name="CPassword" class="form-control" placeholder="Confirm Password" required>
<button class="btn btn-lg btn-primary btn-block" type="reg" name="reg" value="Register">Register</button>
</form>
require_once 'connect.php';
if (isset($_POST['reg'])){
//$dob = $_POST['date'];
$dob = date('Y-m-d', strtotime($_POST['date']));
$Student_ID = $_POST['Student_ID'];
$gender = $_POST['gender'];
$course = $_POST['Course'];
$email = $_POST['inputEmail'];
$password = $_POST['inputPassword'];
$cpassword = $_POST['CPassword'];
$FN = $_POST['FirstName'];
$SN = $_POST['SecondName'];
if ($password === $cpassword) {
// success!
$sql = "INSERT INTO tblaccounts (Email, Password, Student_ID, FirstName, SecondName, Course, Gender, DoB) VALUES ('".$email."','".$password."','".$Student_ID."','".$FN."','".$SN."','".$course."','".$gender."','".$dob."')";
$result = mysqli_query($connection, $sql) or die("Database Connection Failed" . mysqli_error($connection));
//$count = mysqli_num_rows($result);
echo "Registeration Successful!:";
header('Location: login.php');
}
else {
// failed :(
}
} else {
echo "Registeration Failed!:";#
?><br/>Go back to the login screen.<?php
}
I'm not sure to understand your question, in fact your code seems (in a crude way) to achieve your goal. However your script will fail at the time to redirect to login.php using header(), due you already have sent information to the client. That happens when you process your data in the same script you have used to display the form fields. I recommend you to send the form's data to another script.
i'm trying to make the sign in and the sign up within the same page in a website i have this form in html
<form name="form1" action="check_login.php" method="post">
<input type="email" id= "email" name="email" required="required" placeholder="Email Address" />
<input type="password" id= "password" name="password" required="required" placeholder="Password"/>
<span><input type="checkbox" class="checkbox">Keep me signed in</span>
<button name="login" type="submit" class="btn btn-default">Login</button>
</form>
and the form
<form name="form2" action="check_login.php" method="post">
<input type="text" id= "fname" name="fname" required="required" placeholder="First Name"/>
<input type="text" id= "mname" name="mname" required="required" placeholder="Middle Name"/>
<input type="text" id= "lname" name="lname" required="required"placeholder="Last Name"/>
<input type="email" id= "email" name="nemail"required="required" placeholder="Email "/>
<input type="password" id= "password" name="npassword"required="required" placeholder="Password"/>
<input type="password" id= "cpassword" name="cpassword"required="required"placeholder="Confirm Password"/>
<select name='gender' class='col-sm-4'>
<option value='male'>male</option>
<option value='female'>female</option>
</select>
<div class='col-sm-offset-8'>
<button name="sign_up" type="submit" class="btn btn-default">Sign up</button> </div>
</form>
they are in the same page and both navigate to other page within my website then i have this code in php
if (!empty($_POST['login']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql_stmt="select email, password from users where email = '"
.$email."' and password ='".$password."'";
$result= mysqli_query($connection,$sql_stmt);
if ($result)
{
header ("location: index.php");
}
else {
header ("location: login.php");
}
}
if(!empty($_POST['sign_up']))
{
$fname=$_POST['fname'];
$mname=$_POST['mname'];
$lname=$_POST['lname'];
$gender=$_POST['gender'];
$nemail=$_POST['nemail'];
$npassword=$_POST['npassword'];
//if email is already stored ?
$signup="INSERT INTO `users`(`first_name`, `middle_name`, `last_name`,"
. " `gender`, `email`, `password`)"
. " VALUES ('".$fname."','".$mname."','".$lname."','".$gender.
"','".$nemail."','".$npassword."')";
$result1= mysqli_query($connection, $signup);
if ($result1)
{
header ("location: index.php");
}
else {
header ("location: login.php");
}
}
but the navigation to the index never happen!
First things first you need to validate your user input before storing in the db and also you need to hash your passwords, you can read more about hashing here and also read the FAQ here
Also read about prepared statements whether u use MySQLi or pdo read here :
<?php
if (isset($_POST['login'])) {
$email = userInput($_POST['email']);
$password = userInput($_POST['password']); // verify your password you can learn
$sql_stmt = $connection->prepare("SELECT email,password FROM users where email =? ");
$sql_stmt->bindValue(1, $email);
$sql_stmt->execute();
$results = $sql_stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results > 0 && password_verify($password, $results['password']))) {
$_SESSION['username'] = $results['email'];
header("location:page"); //Login details are correct redirect to page after correct
} else { //email and password do not match
//Return your error message
}
}
if (isset($_POST['sign_up'])) {
$fname = userInput($_POST['fname']);
$mname = userInput($_POST['mname']);
$lname = userInput($_POST['lname']);
$gender = userInput($_POST['gender']);
$nemail = userInput($_POST['nemail']);
$npassword = userInput(password_hash($_POST['npassword'], PASSWORD_DEFAULT));
// check if email already stored/
$sql_stmt = $connection->prepare("SELECT email from users where email = ?");
$sql_stmt->bindValue(1, $nemail);
$sql_stmt->execute();
$results = $sql_stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
//Email exist print message
} else {
//email does not exist register the user
$sql_stmt = $connection->prepare("INSERT INTO users (first_name, middle_name, last_name,gender, email, password) value(?,?,?,?,?,?) ");
$sql_stmt->execute(array(
1 => $fname,
2 => $mname,
3 => $last_name,
4 => $gender,
5 => $nemail,
6 => $npassword
));
//Print succcess message;
header(); // redirect where u want
}
}
function userInput($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
can anyone help me where exactly I am going wrong with this code? I got wrong when I am trying to check if email already exists in database or not.
how can I check if email exists in DB or not?
<html>
<h1> Registration Form </h1>
<body>
<form method="post" action="">
<input type="text" name="fname" placeholder="first name" required><br><br>
<input type="text" name="lname" placeholder="last name" required><br><br>
<input type="text" name="mail" placeholder="mail" required> <br><br>
<input type="PASSWORD" name="pass1" placeholder="password" required> <br><br>
<input type="PASSWORD" name="pass2" placeholder="repeat password" required> <br> <br>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 !== $pass2)
{
echo "password in correct ";
}
else
{
$db = mysqli_connect("localhost","root","","reviewsystem");
$check = "SELECT * FROM registers WHERE $mail = email";
if($check == TRUE){
echo "email already exists";
}
else{
$query = "INSERT INTO registers(fname,lname,email,password) VALUES('$fname','$lname','$mail','$pass1')";
mysqli_query($db,$query);
echo " you are registered succesfully";
}
}
}
?>
</body>
</html>
First thing first: you didn't perform any kind of query. You just created a string. Add a line:
$db = mysqli_connect("localhost","root","","reviewsystem");
$check = "SELECT * FROM registers WHERE $mail = email";
$result = mysqli_query($db, $check); //i think there is a typo, mysqi_query
After that you can use mysqli_num_rows which returns number of SELECT rows that came back from DB to identify if the entry already exists:
if(mysqli_num_rows($result) > 0){
echo "email already exists";
}
The problem is in your where clause of mysql query . You must write it as
$check = "SELECT * FROM registers WHERE email = '".$mail."'"; if($check == TRUE){ echo "email already exists"; } else{
I have been making a login/register system and one problem I have run into is not allowing duplicate email addresses from being registered. I want it to work so that the database wont accept data from a duplicate email and the user will be alerted too. I am sort of new to PHP so I am unsure of how to do this. Thanks.
My PHP
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._- ]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your Email Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$username', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?>
The HTML
<form action="./index.php#openModal2" method="post" class="registration_form">
<fieldset>
<legend>Registration Form </legend>
<p>Create A new Account</p>
<div class="elements">
<label for="username">Name :</label>
<input type="text" id="username" name="username" size="25" />
</div>
<div class="elements">
<label for="email">E-mail :</label>
<input type="text" id="email" name="email" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="Password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</div>
Add a unique constraint on the email column in the table members:
ALTER TABLE members ADD UNIQUE (email);
Typically, you would do this when you create the table rather than altering the table afterwards.
Either add a unique constraint as Gordon Linoff said, or here is what I do..
$check_email_for_duplicates = mysqli_query($dbc, "select * from `members` where `Email` = '".mysqli_real_escape_string($email)."'");
if(mysqli_num_rows($check_email_for_duplicates) > 0) //Email address is unique within this system and must not be more than one
{
echo 'Sorry, the email <b>'.$email.'</b> is already in use. Please enter a different email.';
}
else {
//some code
}