I'm trying to insert data into the 'riders' table in the 'poo12104368' database using a form. Currently I am having problems with my 'if' statements because they are not working as they should be. For example, if a user was to only type in a last name and an email address, it would let them create an account. When the user does create an account by entering their correct details into the feilds it should take them to 'newaccount.php'. Can anybody help? Thanks
Code:
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
echo "Something is wrong";
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
echo "<b>Please enter a first name</b>";
}
else if($_POST['lastname'] == null){
echo "<b><p>Please enter a last name</p></b>";
}
else if($_POST['suemail'] == null){
echo "<b><p>Please enter an email</p></b>";
}
$dblink = mysql_connect("localhost", "root", "" )
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required inputs
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
Try this it will work :
Use flag to handle the validation errors in the form use this $error as a flag.
Code :
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
$error = 0;
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
$msg = "something going wrong";
$error = 1;
}
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
$error = 1;
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
$error = 1;
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
$error = 1;
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
$msg = "Please enter a first name";
$error = 1;
}
else if($_POST['lastname'] == null){
$msg = "Please enter a last name";
$error = 1;
}
else if($_POST['suemail'] == null){
$msg = "Please enter an email";
$error = 1;
}
if($error == '0')
{
$dblink = mysql_connect("localhost", "root" , "")
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required standards
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
else
{
echo $msg;
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
I hope it will work for you.
Related
index.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
</style>
</head>
<body>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = "";
$name = $email = $username = $password = $DateOfBirth = $department = $age = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$usernameErr = "username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password)) {
$passwordErr = "Password must be alphanumeric and atleast 6 characters
long!";
}
}
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "AGE is required";
} else {
$age = test_input($_POST["age"]);
}
if ($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "") {
$check = "SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli, $check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($da[0] > 1) {
echo "Username Already in Exists<br/>";
}
else {
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,
`Date_of_birth` , `department` ,`age`)
VALUES ('','" . $username . "', '" . $hashed_password . "', '" . $email . "' ,
'" . $name . "' , '" . $DateOfBirth . "' , '" . $department . "' , '" . $age . "')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px">
<h2>Registration Form</h2>
<p><span class="error">All fields are required </span></p>
<form method="post" action="">
Name:
<input type="text" name="name" style="margin-left: 52px">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email" style="margin-left: 48px">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
Username:
<input type="text" name="username" style="margin-left:26px">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
Password:
<input type="password" name="password" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
Date Of Birth :
<input type="date" name="Date_of_birth">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
Age :
<input type="number" name="age" style="margin-left:62px">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
Department :
<select name="department" style="margin-left:14px">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<input type="submit" name="submit" value="Register">
</form>
</div>
</body>
</html>
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'amith';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
i'm creating a simple php registration form, i only have one issue which is not getting fixed i.e., when any one while registering enters the same username then an error message should throw saying that username already taken i have tried with the above code but its not working. please can any one help me to fix my issue.
before
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` ,
`name` , `Date_of_birth` , `department` ,`age`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' ,
'".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."')";
You can write SQL to check if username is exist or not :
SQL : 'SELECT username from users where username = $username';
If this query returns result with count more than 0 then show an error message as 'This Username already exists';
If it gives you 0 results then proceed with INSERT functionality.
Before you insert the new user you can query for the username with a select like:
SELECT username FROM users WHERE username='$username'
If this query returns more than 0 rows the username exists already.
Hi you can try like this
variable should be like this $_POST['username']
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,`Date_of_birth` , `department` ,`age`) VALUES ('', ".$username.", ".$hashed_password.", ".$email." , ".$name." , ".$DateOfBirth." , ".$department." , ".$age.")";
An effective way to tackle this unique username problem is to validate the username at the time of entry from UI.
Step 1:in html input box there should be jquery or js function call to a php page with entered username as argument.
Step 2 the backend php scrpt will simple check the username in database and if exists the will return a JSON o/p that userbane alreasy exist else it will return true.
Step 3:show the message to on UI with simple Js and block further processing of form.
Also you must check the uniqueness of username after form submit and before insert into your data base table to avoid concurrent submit by two different user with same username.
Also if possible make sure username is primary key in your database table to avoid concurrent submit with same username problem,This will add another solid layer of protection at the bottom.
<input type="text" name="uname" id="uname" onblur="unameOnBlur(this.value);">
You can do it onkeyup or any suitable event also.
inside unameOnBlur make an ajax call like
$.ajax({
url: 'json_uname.php?uname=' + uname,
dataType: 'json'
}).done(function (j){
if(username unique)
//your action code
})
the above one is sample ajax call example
Json_uname.php page is simple to write to check against db.
Am just getting my hand on php and I need some little help please. I am working on a registration form with server-side validation, then after validation, the form input should be submitted to the database. I entered data, click submit button, but the data were not submitted to the database. There is no error message. I like you to help me point out where have been wrong and give me a possible solution. Thanks.
Index.php
<?php
include ('signup.php');
?>
<div class="maindiv">
<div class="login"></div>
<div class="wrapper">
<div class="pageintro">
<p>PHP</p>
<p>PROJECT 1</p>
</div>
<div class="regform">
<form name="reg" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<p class="regformp">Fill all Fields</p>
<div class="regwrap">
<div class="inp">Full Name</div>
<div class="inp1"><input type="text" name="FullName" value="<?php echo $FullName; ?>"></div>
<span class="error"><?php echo $fullnameErr;?></span>
<div class="inp">E-Mail</div>
<div class="inp1"><input type="text" name="Email" value="<?php echo $Email; ?>"></div>
<span class="error"><?php echo $emailErr;?></span>
<div class="inp">Password</div>
<div class="inp1"><input type="password" name="Password"></div>
<span class="error"><?php echo $passwordErr;?></span>
<div class="inp">Confirm Password</div>
<div class="inp1"><input type="password" name="ConfirmPassword"></div>
<span class="error"><?php echo $conpasswordErr;?></span>
<div class="inp">Gender</div>
<div class="inp1"><input type="radio" name="Gender" value="Male" <?php if(isset($Gender)&& $Gender=="Male") echo "checked"; ?> >Male <input type="radio" name="Gender" <?php if(isset($Gender)&& $Gender=="Female") echo "checked"; ?> Value="Female">Female</div>
<span class="error"><?php echo $genderErr;?></span>
<div class="inp">Date Of Birth</div>
<div class="inp1"><select name="DayOfBirth"><option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option></select> <select name="MonthOfBirth"><option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option></select> <select name="YearOfBirth"><option>1970</option>
<option>1971</option>
<option>1972</option>
<option>1973</option>
<option>1974</option></select></div>
<span class="error"><?php echo $dobErr;?></span>
<span class="error"><?php echo $mobErr;?></span>
<span class="error"><?php echo $yobErr;?></span>
<div class="inp2"><input type="submit" name="submit" value="SIGN UP"></div></div>
</form>
signup.php
<?php
include ('project1db.php');
//Define variables
$fullnameErr="";
$emailErr="";
$passwordErr="";
$conpasswordErr="";
$genderErr="";
$dobErr="";
$mobErr="";
$yobErr="";
$FullName="";
$Email="";
$Password="";
$ConfirmPassword="";
$Gender="";
$DayOfBirth="";
$MonthOfBirth="";
$YearOfBirth="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["FullName"])){
$fullnameErr = "Name is required";
}
else{
$FullName = test_input($_POST["FullName"]);
//Check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z]*$/",$FullName)){
$fullnameErr = "Enter Valid name please!";
}
}
if(empty($_POST["Email"])){
$emailErr = "Email is required";
}else{
$EMail = test_input($_POST["Email"]);
//Check if e-mail address is correct
if(!filter_var($EMail, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email address";
}
}
if(empty($_POST["Password"])){
$passwordErr = "Password is required";
}else{
$Password = test_input($_POST["Password"]);
//Check password
if(!preg_match("/^[a-z0-9]{6,}$/",$Password)){
$passwordErr = "Password should contain 6+ characters, lowercase and numbers!";
}
}
if(empty($_POST["ConfirmPassword"])){
$conpasswordErr = "Confirm your Password!";
}
else{
$ConfirmPassword = test_input($_POST["ConfirmPassword"]);
//Confirm if password match
if($ConfirmPassword != $Password){
$conpasswordErr = "Password not match!";
}
}
if(empty($_POST["Gender"])){
$genderErr = "Select your Gender!";
}else{
$Gender = test_input($_POST["Gender"]);
}
if(empty($_POST["DayOfBirth"])){
$dobErr = "Select your Day Of Birth";
}else{
$DayOfBirth = test_input($_POST["DayOfBirth"]);
}
if(empty($_POST["MonthOfBirth"])){
$mobErr = "Select your Month Of Birth";
}else{
$MonthOfBirth = test_input($_POST["MonthOfBirth"]);
}
if(empty($_POST["YearOfBirth"])){
$yobErr = "Select your Year Of Birth";
}else{
$YearOfBirth = test_input($_POST["YearOfBirth"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = ""){
$sql = "INSERT into usersignup (FullName, Email, Password, Gender, DayOfBirth, MonthOfBirth, YearOfBirth) VALUES(?,?,?,?,?,?,?)";
if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssisi", $FullName, $Email, $Password, $Gender, $DayOfBirth, $MonthOfBirth, $YearOfBirth);
/* Set the parameters values and execute
the statement again to insert another row */
$FullName = $_REQUEST['FullName'];
$Email = $_REQUEST['Email'];
$Password = $_REQUEST['Password'];
$Gender = $_REQUEST['Gender'];
$DayOfBirth = $_REQUEST['DayOfBirth'];
$MonthOfBirth = $_REQUEST['MonthOfBirth'];
$YearOfBirth = $_REQUEST['YearOfBirth'];
$stmt->execute();
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
else{
}
?>
Database Connection
project1db.php
<?php
$dbhost = 'localhost:3308';
$dbuser = 'root';
$dbpass = '';
$dbname = 'phpproject';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: '.mysqli_error());
}
echo 'Connected successfully';
I have figured out the problem and the problem have been solved.
First problem is with the Mysql database. The AutoIncrement colunm precisely was not set to AutoIncrement. So, I open PhpMyadmin to alter and set the Id colunm to AutoIncrement.
Second Problem was with the conditional statement here:
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = "")
The correct line of code which later worked properly is:
if(empty($fullnameErr) && empty($emailErr) && empty($passwordErr) && empty($conpasswordErr) && empty($genderErr) && empty($dobErr) && empty($mobErr) && empty($yobErr))
This is an important information for those who got confused after they have validated the data input but didn't know how to save the data into the database table.
I am trying build a simple registration form with validation. When I leave a field blank and submit my form I keep getting this error undefined index email or undefined index password.For eg I fill in all fields except lastname I will get a notice saying email is undefined and if i fill all the fields I get username ,email and password is undefined. I googled it and the sugesstions i could get was isset , I tried using isset but it still does not work. Can anyone please help?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
$Firstname=isset($_SESSION['Firstname']);
$Lastname=isset($_SESSION['Lastname']);
$username=isset($_SESSION['username']);
$email=isset($_SESSION['email']);
$password=isset($_SESSION['password']);
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="registerUser.php" method="post" >
<p>
<label for="Firstname">First Name:</label>
<input name="Firstname" type="text" id="Firstname" size="30"/>
</p>
<p>
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/>
</p>
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
<p>Login</p>
</body>
</html>
Here is registeruser.php
<?php
session_start();
include('dbconnect.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['FirstName'] == '')
{
$_SESSION['error']['Firstname'] = " FirstName is required.";
}
if($_POST['LastName'] == '')
{
$_SESSION['error']['Lastname'] = " LastName is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2)
{
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
When you do not fill a field, its index will not exist in the $_POST associative array. You need to check with isset whether it exists like this:
<?php
session_start();
include('dbconnect.php');
$_SESSION['error'] = array();
if(isset($_POST['submit'])) {
//whether the username is blank
if((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == '')) {
$_SESSION['error']['Firstname'] = " FirstName is required.";
if((!isset($_POST['LastName'])) || ($_POST['LastName'] == '')) {
$_SESSION['error']['Lastname'] = " LastName is required.";
if((!isset($_POST['email'])) || ($_POST['email'] == '')) {
$_SESSION['error']['email'] = "E-mail is required.";
} else {
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email'])) {
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0) {
$_SESSION['error']['email'] = "This Email is already used.";
}
} else {
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if((!isset($_POST['password'])) || ($_POST['password'] == '')) {
$_SESSION['error']['password'] = "Password is required.";
}
if((!isset($_POST['username'])) || ($_POST['username'] == '')) {
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2) {
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
For example
((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == ''))
will be true if there is no 'FirstName' in $_POST or it is an empty string. The trick is that the second operand will not be checked if the first is true, preventing the problem you have mentioned in the question.
Further observations:
your code assumes that there is a $_SESSION['error'] element. You might get errors if this is not properly initialized
your code is vulnerable to SQL injection
your code is not properly structured, which makes it difficult to maintain
your code mixes up sql with php, which is not elegant
The first issue is that your HTML input names don't match the PHP names you expect.
if($_POST['FirstName'] == '') //Upper case N
While in the markup you use <input name = "Firstname" ... with lower case N
Another issue with the markup is two inputs are named Firstname:
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/> <!--Firstname should be Lastname-->
Finally one more problem lies within the index.php file where you try to flash the session variable which comes back from the registerUser.php. Either there should be only one $SESSION["error"] or isset(SESSION["error"]["field"]) must be used just like with the $POST["field"] in registerUser.php.
The flashing code would look like this after the change:
if(isset($_SESSION['error']))
{
if (isset($_SESSION['error']['Firstname'])) echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
if (isset($_SESSION['error']['Lastname'])) echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
if (isset($_SESSION['error']['username'])) echo '<p>'.$_SESSION['error']['username'].'</p>';
if (isset($_SESSION['error']['email'])) echo '<p>'.$_SESSION['error']['email'].'</p>';
if (isset($_SESSION['error']['password'])) echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
I would also suggest looking up a good resource on the topic. Login/Register systems are hard to get right for the first time.
// php code start------------->
<?php
// define variables and set to empty values
$nameErr=$empidErr=$usernameErr=$passwordErr="";
$name=$empid=$username=$password="";
if(isset($_POST['submit']))
{
if (empty($_POST["empid"])) {
$empid = "";
} else {
$empid = test_input($_POST["empid"]);
}
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["etype"])) {
$etype = "";
} else {
$etype = test_input($_POST["etype"]);
}
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9A-Za-z ^-_#. ]*$/",$password)) {
$passwordErr = "Only letters and white space allowed";
}
}
}
//collect the data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if((strlen($name)>0)&&(strlen($empid)>0)&&(strlen($etype)>0)&&(strlen($username)>0)&&(strlen($password)>0))
{
include "connection.php";
//Here to check the username is aleady present in database or not
$query = mysql_query("SELECT * FROM signin WHERE username='$username' ", $con);
//$result = mysql_query($query) or die('Error: ' . mysqli_error($con));
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
else
{
//if not present in database then create the new user in database.
$sql="INSERT INTO signin (emp_name,emp_id,emp_type,username,password,create_datetime)
VALUES ('$name','$empid','$etype','$username','$password',now())";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<script>alert('New User Added Successfully');</script>";
echo"<script>window.location.href = 'login.php';</script>";
}
mysqli_close($con);
}
?>
//php code end------------<
//html code------------------>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend> <b><i> Information</i></b></legend><br>
Employee ID:-<input type="text" name="empid" placeholder="Enter Employee ID" size="10" value="<?php echo $rum1?>" readonly>
Employee Name:-<input type="text" name="name" placeholder="Surname Middlename Father Name" size="50" value="<?php echo $rum2;?>" readonly>
Employee Type:-<input type="text" name="etype" placeholder="Type" value="<?php echo $rum3;?>" readonly><br /><br />
Username:-<input type="text" name="username" id="loginid" placeholder="Username" size="30" value="<?php echo $unm;?>">
<span class="error">* <?php echo $usernameErr;?></span> <br /><br />
Password:-<input type="password" id="password" name="password" size="30">
<span class="error">* <?php echo $passwordErr;?></span> <br />
</fieldset>
<br>
<input name="submit" type="submit" value="Submit">
<input name="reset" type="submit" value="Reset">
<br ><br >
</form>
</fieldset>
</body>
</html>
//html code end---------------------<
In above php code is work but i want to check username.if the username present in the database then give the alert as the user is already present in the database change the username please. So please sir or madam suggest any code or changes in this php code and suggest any solution to check the user present in database or not.if user first time register then new user is added and if user multiple second time register then give alert is user already register please do your login.
to know if present mysql_num_rows should return 1 or special cases more than one
so change this
if (mysql_num_rows($query) <=0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
To this
if (mysql_num_rows($query) >0)
{
echo "<script>alert('User already Exists Change the username');</script>";
echo"<script>window.location.href = 'signin.php';</script>";
}
Dont use mysql function as they are depriciated. Learn mysqli or PDO
I am trying to enable a user to change their password on their account when logged in. However, I cant seem to get it to work.
Do you have any suggestions?
<?php
if ($_POST['submitEmail'])
{
$newemail = $_POST['email'];
$newemail = stripslashes($newemail);
$newemail = str_replace("'", "'", "$newemail");
//checks database to see if email user types in already exists
$query = "SELECT * FROM users WHERE email = '$newemail'";
$result = mysqli_query($db_connection, $query);
$nums = mysqli_num_rows($result);
if ($nums >= 1)
{
//if email already exists, inform user
echo "Email already exists";
echo "<br/>Click <a href = 'account.php?page=email'> HERE</a> to try again";
}
else
{
//if email does not already exist, update users email
$querychange = "UPDATE users SET email = '$newemail' where id = '$userID'";
$result3 = mysqli_query($db_connection, $querychange);
echo "Your Email has been changed";
}
}
else {
echo "<strong> Current Email: </strong>$email ";
?>
<!-- Allows users to enter new email address -->
<form name="changeEmail" id="changeEmail" method="post" action="account.php?page=email">
<input type="hidden" value="email" name="account_submit_type"/>
<input type='hidden' name='changeEmail' value='yes'>
<strong> Email </strong><input type = "text" name = "email" size="40" value=""> <br>
<input type ="button" value="submitEmail" onclick="verifyForm()"/>
</form>
<?php
}
?>
<input type ="button" value="submitEmail" onclick="verifyForm()"/>
This has to be
<input type="submit" value="submitEmail"/>
Another error: Undefined $email:
echo "<strong> Current Email: </strong>"; echo $email;
has to be like this:
echo "<strong> Current Email: </strong>"; echo $_POST['email'];
Full version which works for me:
<?php
if ($_POST['submitEmail'])
{
$newemail = $_POST['email'];
$newemail = stripslashes($newemail);
$newemail = str_replace("'", "'", "$newemail");
//checks database to see if email user types in already exists
$query = "SELECT * FROM users WHERE email = '$newemail'";
$result = mysqli_query($db_connection, $query);
$nums = mysqli_num_rows($result);
if ($nums >= 1)
{
//if email already exists, inform user
echo "Email already exists";
echo "<br/>Click <a href = 'account.php?page=email'> HERE</a> to try again";
}
else
{
//if email does not already exist, update users email
$querychange = "UPDATE users SET email = '$newemail' where id = '$userID'";
$result3 = mysqli_query($db_connection, $querychange);
echo "Your Email has been changed";
}
}
else {
echo "<strong> Current Email: </strong>"; echo $_POST['email'];
?>
<!-- Allows users to enter new email address -->
<form name="changeEmail" id="changeEmail" method="post" action="#?page=email">
<input type="hidden" value="email" name="account_submit_type"/>
<input type='hidden' name='changeEmail' value='yes'>
<strong> Email </strong><input type = "text" name = "email" size="40" value=""> <br>
<input type="submit" value="submitEmail"/>
</form>
<?php
}
?>