I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...
Related
I'm trying to create a PHP registration script using PDO prepared statements with positional placeholders. But the MySQL queries don't execute. var_dump(); doesn't display any error.
I desperately need someone to closely look at my code and explain to me why the queries don't execute.
Below is a rewrite of register.php, which now displays errors, if certain, predefined conditions are not met. However, it doesn't display any error, when the insert or select query fail. var_dump(); doesn't display any error either, even though PDO queries fail to execute.
Please, I need your help to fix this. Your time and input are much appreciated in advance. Thanks.
register.php:
<?php
// include configuration file
require ("includes/config.php");
//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("classes/upload/upload_class.php");
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = "";
$firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = "";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$firstname = student_input($_POST["firstname"]);
$lastname = student_input($_POST["lastname"]);
$username = student_input($_POST["username"]);
$gender = student_input($_POST["gender"]);
$password = student_input($_POST["password"]);
$confirmation = student_input($_POST["confirmation"]);
$email = student_input($_POST["email"]);
$birthday = student_input($_POST["birthday"]);
$phone = student_input($_POST["phone"]);
// validate submission
if (empty($_POST["firstname"]))
{
$firstnameErr = "First name is required.";
}
else
{
$firstname = student_input($_POST["firstname"]);
}
if(empty($_POST["lastname"]))
{
$lastnameErr = "Last name is required.";
}
else
{
$lastname = student_input($_POST["lastname"]);
}
if(empty($_POST["username"]))
{
$usernameErr = "Username is required.";
}
else if(!empty($_POST["username"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
{
$usernameErr = "Username must contain only letters and numbers.";
}
if (strlen($username) < 4 || strlen($username) > 10)
{
$usernameErr = "Username must be from 4 to 10 characters.";
}
}
else
{
$username = student_input($_POST["username"]);
}
if(empty($_POST["gender"]))
{
$genderErr = "Gender is required.";
}
else
{
$gender = student_input($_POST["gender"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "Enter a password.";
}
else if(!empty($_POST["password"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
{
$passwordErr = "Password must contain letters, numbers and special characters.";
}
if (strlen($password) < 8 || strlen($password) > 20)
{
$passwordErr = "Password must be from 8 to 20 characters.";
}
}
else if (empty($_POST["confirmation"]))
{
$confirmationErr = "Confirm your password.";
}
else if ($_POST["password"] != $_POST["confirmation"])
{
$confirmationErr = "Password and confirmation don't match.";
}
else
{
$password = student_input($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "Your email address is required.";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
else
{
$email = student_input($_POST["email"]);
}
if(empty($_POST["birthday"]))
{
$birthdayErr = "Birthday is required.";
}
else if(!empty($_POST["birthday"]))
{
$today = date("d-m-Y");
$diff = date_diff(date_create($birthday), date_create($today));
if($diff->format('%y%') < 6)
{
$birthdayErr = "You must be at least 6 years old to register.";
}
else
{
$birthday = student_input($_POST["birthday"]);
}
}
if(empty($_POST["phone"]))
{
$phoneErr = "Phone number is required.";
}
else if(!empty($_POST["phone"]))
{
// Don't allow country codes to be included (assumes a leading "+")
if (preg_match('/^(\+)[\s]*(.*)$/',$phone))
{
$phoneErr = "You should not include the country code.";
}
// Remove hyphens - they are not part of a telephone number
$phone = str_replace ('-', '', $phone);
// Now check that all the characters are digits
if (!preg_match('/^[0-9]{10,11}$/',$phone))
{
$phoneErr = "Phone number should be either 10 or 11 digits";
}
// Now check that the first digit is 0
if (!preg_match('/^0[0-9]{9,10}$/',$phone))
{
$phoneErr = "The telephone number should start with a 0";
}
else
{
$phone = student_input($_POST["phone"]);
}
}
else if(!empty($_FILES["userimage"]))
{
//This is the directory where images will be saved
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
$my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = false;
$my_upload->the_temp_file = $_FILES['userimage']['tmp_name'];
$my_upload->the_file = $_FILES['userimage']['name'];
$my_upload->http_error = $_FILES['userimage']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
{
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
$imagename = $my_upload->file_copy;
}
else
{
$imagename = "";
}
}
else
{
try
{
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute(student_input($_POST["username"]));
$user = $stmt->fetch(); # get users data
if($user["username"]==$username)
{
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($user["email"]==$email)
{
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if($user["phone"]==$phone)
{
$errorMsg[]="Sorry, the phone number already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMs g" show then continue
{
$new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash()
// insert form input into database
$stmt= $pdo->prepare("INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute($data);
// find out user's ID
$stmt = $pdo->query("SELECT LAST_INSERT_ID() AS user_id");
$user_id = $stmt[0]["user_id"];
// redirect to list users page
header("Location: userinfo.php");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
// render the header template
include("templates/header.php");
// render add user template
include("templates/register-form.php");
// render the footer template
include("templates/footer.php");
?>
I have the following, relevant code in functions.php, which is called by the config.php:
// validate user input
function student_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Another thing: how do I print the errors on the register-form.php right below any existing error's input field?
register-form.php:
<br>
<br>
<h1>Register</h1>
<br>
<form enctype="multipart/form-data" action="register.php" method="post">
<fieldset>
<div class="form-group">
<label>First Name:</label><span class ="error">*</span> <input autofocus class="form-control" name="firstname" placeholder="First Name" type="text"/>
<span class = "error"><?php //echo $errorMsg["firstname"];?></span>
</div>
<div class="form-group">
<label>Last Name:</label><span class ="error">*</span> <input class="form-control" name="lastname" placeholder="Last Name" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["lastname"];?></span>
</div>
<div class="form-group">
<label>Username:</label><span class ="error">*</span> <input class="form-control" name="username" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["username"];?></span>
</div>
<div class="form-group">
<label>Gender:</label><span class ="error">*</span> <select class="form-control" name="gender" value="gender">
<option value="">Select your gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Password:</label><span class ="error">*</span> <input class="form-control" name="password" type="password"/ autocomplete="off"><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Confirm Password:</label><span class ="error">*</span> <input class="form-control" name="confirmation" type="password"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Email:</label><span class ="error">*</span> <input class="form-control" name="email" placeholder="Email" type="text"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Phone:</label><span class ="error">*</span> <input class="form-control" name="phone" placeholder="Phone" type="tel" min="10" max="11"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Date of Birth:</label><span class ="error"></span> <input class="form-control" name="birthday" placeholder="birthday" type="date" /><br />
<span class = "error"><?php //echo $error[birthday];?></span>
</div>
<div class="form-group">
<label>Passport Photo:</label><input class="form-control" name="userimage" id="fileimage" placeholder="Your Photo" type="file"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="Register" value="Register">Register</button>
</div>
</fieldset>
</form>
<div>
or Login
</div>
<br/>
<br>
<br>
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I hope someone can shed some light on this issue. I have created a registration form that submits to a second page for validation. there are various checks to catch errors and unwanted user input and is failing on checking for empty fields.. even if all the fields have data in them, it is still being returned as empty
here is my form - note it does include a hidden field to which it was suggested to use a /> instead of the usual > tag - either way makes no difference
<form id="registersocial" class="SRF" name="registersocial" action="php.includes/rasocial.inc.php" method="POST">
<div id="formheaders"><strong>Personal Details</strong></div>
<br/>
<fieldset>
<lable><strong>First Name</strong><br/>
<input type="text" name="firstname" id="firstname" class="SRF" onKeyup="restrict('firstname')" placeholder="First Name" >
<span id="Errmsg-first"></span>
</lable>
<br/>
<lable><strong>Last Name</strong><br/>
<input type="text" name="lastname" id="lastname" class="SRF" onKeyup="restrict('lastname')" placeholder="Last Name" >
<span id="Errmsg-last"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Date of Birth</strong><br/>
<select name="birthmonth" id="birthmonth" class="SRF">
<?php require("php.includes/month.inc.php"); ?>
</select>
<span id="Errmsg-mob"></span>
<input type="text" name="birthday" id="birthday" class="SRF" maxlength="2" placeholder="Day">
<span id="Errmsg-dob"></span>
<input type="text" name="birthyear" id="birthyear" class="SRF" maxlength="4" placeholder="Year">
<span id="Errmsg-yob"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Location</strong><br/>
<select name="country" id="country">
<?php require("php.includes/countrylist.php"); ?>
</select>
<span id="Errmsg-country"></span>
</lable>
<br/>
</fieldset>
<hr class="SRF">
<div id="formheaders"><strong >Account Information</strong></div>
<br/>
<fieldset>
<input type="hidden" name="accounttype" id="accounttype" class="SRF" value="Social"/>
<lable><strong>Create a Username</strong><br/>
<input type="text" name="username" id="username" class="SRF" onKeyup="restrict('username')" onblur="checkusername()" placeholder="Username" >
<span id="Errmsg-username"></span>
</lable>
<br/>
<lable><strong>Your Current Email</strong><br/>
<input type="email" name="email" id="email" class="SRF" onKeyup="restrict('email')" placeholder="Your Email" >
<span id="Errmsg-email"></span>
</lable>
<br/>
<lable><strong>Create a Password</strong><br/>
<input type="password" name="pwd" id="pwd" class="SRF" placeholder="Password" >
<span id="Errmsg-password"></span>
</lable>
<br/>
<br/>
<input type="submit" id="submit" name="submit" value="submit">
</fieldset>
<br/>
<span id="status"></span>
<br/>
</form>
below is the file that gets the posted data and runs through validation file name is rasocial.inc.php - again my issue is that upon completing the form, I am getting a empty error in the url - I am sure it is simple but cannot see it for the life of me
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
include_once("ctb.inc.php");
$fn = mysqli_real_escape_string($pdo, $_POST['firstname']);
$ln = mysqli_real_escape_string($pdo, $_POST['lastname']);
$bm = mysqli_real_escape_string($pdo, $_POST['birthmonth']);
$bd = mysqli_real_escape_string($pdo, $_POST['birthday']);
$by = mysqli_real_escape_string($pdo, $_POST['birthyear']);
$co = mysqli_real_escape_string($pdo, $_POST['country']);
$at = mysqli_real_escape_string($pdo, $_POST['accounttype']);
$un = mysqli_real_escape_string($pdo, $_POST['username']);
$em = mysqli_real_escape_string($pdo, $_POST['email']);
$pwd = mysqli_real_escape_string($pdo, $_POST['pwd']);
var_dump($fn, $ln, $bm, $bd, $by, $co, $at, $un, $em, $pwd);
//Error Handlers
//Check for empty fields
if (empty($fn) || empty($ln) || empty($bm) || empty($bd) || empty($by) || empty($co) || empty($at) || empty($un) || empty($em) || empty($pwd)) {
header("Location: ../registersocial.php?registersocial=empty");
exit();
} else {
//Check firstname and lastname for valid chars
if (!preg_match("/^[a-zA-Z]*$/", $fn) || !preg_match("/^[a-zA-Z]*$/", $ln)) {
header("Location: ../registersocial.php?registersocial=invalidcharacters");
exit();
} else {
//Check birth month has been selected
if ($_POST['birthmonth'] == '0') {
header("Location: ../registersocial.php?registersocial=birthmonth");
exit();
} else {
//Check birth day is numbers only
if (!preg_match("/^[0-9]*$/", $bd)) {
header("Location: ../registersocial.php?registersocial=birthday");
exit();
} else {
//Check the birth day length is 2 characters
if (strlen($bd) != 2 ) {
header("Location: ../registersocial.php?registersocial=birthdaylength");
exit();
} else {
//Check birth year is numbers only
if (!preg_match("/^[0-9]*$/", $by)) {
header("Location: ../registersocial.php?registersocial=birthyear");
exit();
} else {
//Check birth year is 4 characters
if (strlen($by) != 4 ) {
header("Location: ../registersocial.php?registersocial=birthyearlength");
exit();
} else {
//Check country has been selected
if ($_POST['country'] == '0') {
header("Location: ../registersocial.php?registersocial=country");
exit();
} else {
//Check if accounttype has been modified
if (!preg_match("/^[a-zA-Z]*$/", $at) || $_POST['accounttype'] != 'Social') {
header("Location: ../registersocial.php?registersocial=accounttype");
exit();
} else {
//Check username isnt taken
if (!preg_match("/^[a-zA-Z0-9]*$", $un)) {
header("Location: ../registersocial.php?registersocial=invalidusername");
exit();
} else {
//Check username is not taken in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE username =?');
$stmt->execute($un);
$usernamecheck = $stmt->fetch();
if ($usernamecheck > 0 ) {
header("Location: ../registersocial.php?registersocial=usernametaken");
exit();
} else {
//Check email is valid
if (!filter_var($em, FILTER_VALIDATE_EMAIL) ) {
header("Location: ../registersocial.php?registersocial=invalidemail");
exit();
} else {
//Check if email exists in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE email =?');
$stmt->execute($em);
$emailcheck = $stmt->fetch();
if ($emailcheck > 0 ) {
header("Location: ../registersocial.php?registersocial=emailtaken");
exit();
//add dob fields to make date of birth
$dob = new DateTime($by.'-'.$bm.'-'.$bd);
$dob->format('Y-m-d');
//hash password
$hashedpwd = password_hash($pwd, PASSWORD_DEFAULT);
//insert user into db
$stmt = $pdo->prepare("INSERT INTO sh_userdata (username, email, password, accounttype, signupdate, lastlogindate) VALUES (?,?,?,?,NOW(),NOW())");
$stmt->execute(array("$un","$em","$hashedpwd","$at"));
header("Location: ../registersocial.php?registersocial=sucess");
exit();
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
header("Location: ../registersocial.php?registersocial=nopost");
exit();
}
any help or suggestions would be really appreciated
code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>
html code:
<?php echo $msg; ?>
<?php if(!empty($errMsg)) echo '<p style="color:#EA4335;">'.$errMsg.'</p>';?>
<?php if(!empty($succMsg)) echo '<p style="color:#34A853;">'.$succMsg.'</p>';?>
<form method="post">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<input type="text" name="email" id="email" placeholder="Enter Your Email">
<input type="text" name="phone" id="phone" placeholder="Enter Your Phone">
<input type="text" name="message" id="message" placeholder="Enter Your Message" >
<input name="captcha_code" type="text" value="" placeholder="Enter the code" >
<img src="captcha.php" id="capImage"/>
<br/>Can't read the image? click here to refresh.
<input type="submit" name="insert" value="Submit" placeholder="Enter Your Message" >
</form>
When I click on submit button it shows data has been submitted successfully while captcha code is right or worng it insert form value into database. So, how can I fix this problem ?
Thank You
Please use this code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
if($captchaCode == $enteredcaptchaCode)
{
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$msg .= "<h4 style='text-align:center;color:green;'>Your Data Has Not Been Submitted.</h4>";
}
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>
`
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
if (!preg_match("/^\w+$/",$username)) {
$error = true;
$username_error = "Username cant contain space and special characters";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
$result = mysqli_query($connection, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
if ($row['id'] == 1) {
header("Location: priv8/ididthis.php");
} else if ($row['id'] >= 1) {
header("Location: index.php");
} else {
$errormsg = "Incorrect username or Password!";
}
can u see what's wrong with my code ? the $errormsg doesn't showing when the username or the password is wrong..
`
<body>
<div class="layout">
<div class="layout-screen">
<div class="app-title">
<h1>Login</h1>
</div>
<div class="layout-form">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div class="control-group">
<input type="text" name="username" class="login-field" value="" placeholder="username" id="login-username">
<label class="login-field-icon fui-user" for="login-username"></label>
</div>
<div class="control-group">
<span><?php if (isset($username_error)) { echo $username_error; } ?></span>
</div>
<div class="control-group">
<input type="password" name="password" class="login-field" value="" placeholder="password" id="login-pass">
<label class="login-field-icon fui-lock" for="login-pass"></label>
</div>
<div class="control-group">
<span><?php if (isset($password_error)) { echo $password_error; } ?></span>
</div>
<div class="control-group">
<input class="btn btn-primary btn-large btn-block" type="submit" name="login" value="Sign in"/>
</div>
</form>
<span><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
<a class="layout-link" href="forgot.php">Lost your password?</a>
</div>
</div>
</div>
The problem is that your error message is inside this block
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else if ($row['id'] >= 1) {...}
else {
$errormsg = "Incorrect username or Password!";
}
}
This means that the error message is never shown because row id will always be 1 or >=1. To fix, move the error message out, like this:
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else($row['id'] >= 1) {...}
}
else {
$errormsg = "Incorrect username or Password!";
}
This is my registration form I am using both javascript and php for validating form, javascript code works well in showing validation error messages however somethings wrong with php code,when javascript is disabled php code should show form validation error messages by refrshing page on form submit,but no error messages appear and no data is inserted. On clicking submit, page is reloaded but even form does not appear.
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$un = $_POST['username'];
$em = $_POST['email'];
$pswd = $_POST['password'];
$d= date("Y-m-d");
if (strlen($fn) < 2 || strlen($fn) > 15) {
$error = "First name must be 2 to 15 characters long";
}
elseif (strlen($ln) < 2 || strlen($ln) > 15) {
$error = "Last name must be 2 to 15 characters long";
}
elseif($em==""){
$error = "Email cannot be empty";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format";
}
elseif($pswd==""){
$error = "Fill your password";
}
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
}
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
?>
<form action="" method="post">
<input type="text" name="fname" id="fn" placeholder="First Name"/><br />
<input type="text" name="lname" id="ln" placeholder="Last Name"/><br />
<input type="text" name="username" id="un" placeholder="Username" class="username" /><br />
<input type="email" name="email" id="em" placeholder="Email"/> <br />
<input type="password" name="password" id="pswd" placeholder="Password"/><br />
<input type="password" name="password2" id="pswd2" placeholder="Confirm Password"/><br />
<input type="submit" id="submit" name="reg" value="Create an Account">
<center><div id="er"><?php echo $error ?></div></center>
</form>
You should echo $error not $er
<center><div id="er"><?php echo $error; ?></div></center>
You are doing a mistake:
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
You should use 'username' instead of ':username'. like this:
$stmt->execute(array('username'=>$un,'firstname'=>$fn,'lastname'=>$ln,'email'=>$em,'password'=>$pswd));
There are a few inconsistencies in your code.
At the beginnig you assign $_POST['email'] to $em, but later you validate against a variable named $email, which doesn't exist at this point.
$em = $_POST['email'];
.
.
.
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format"; //should maybe be $error
}
Then there is the password-validation:
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
$pswd2 has never been defined in your code.
$stmt ist defined in the else-block of your validation, but you use it for getting the row-count after the validation. So, if any of your if-statements is true, this will cause an error.
It would be better if you change that part of your code to this:
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
After all it seems like you haven't error reporting activatet.