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
}
?>
Related
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.
I am having some trouble with my register form. It is registering new users perfectly, although the validation is causing me issues. When a user with the same username tries to register the validation picks this up perfectly, but i still get the diagloue box poping up confirming the user has successfully registered. I check the database when this happens and the user doesnt reigster as the validation has been carried out. How do I stop this happening?
basically what i am wanting to achieve is for the message to stop saying 'successful' when a new user tries to enter a username which already exists, as the validation is picking this up
Here is my code
<?php
if ($_POST["register"]=="yes") {
//Declares the variables that will be posted to the database
$username = $_POST['username'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = md5($_POST['password']);
//Checks the database to see if username exists already
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($db_connection, $query);
$nums = mysqli_num_rows($result);
//Checks the database to see if email address exists already
$query2 = "SELECT * FROM users WHERE email = '$email'";
$result2 = mysqli_query($db_connection, $query2);
$nums2 = mysqli_num_rows($result2);
if ($nums >= 1)
//informs user if username already exists
echo "Username already exists, click <a href = 'register1.php'>HERE </a> to try again";
else if ($nums2 >=1)
//informs user if email already exists
echo "Email Address already exists, click <a href = 'register1.php'>HERE </a> to try again";
else
{
$insert = 'INSERT INTO users(username, first_name, last_name, email, password,role_id, disable, activate) VALUES("'.$username.'","'.$first_name.'","'.$last_name.'","'.$email.'","'.$password.'", 2,0,0)';
mysqli_query($db_connection, $insert);
mysqli_close($db_connection);
("Location: mainpage.php");
}
{
$i = 1;
if ($i > 0) {
die;
}
else
"<script>alert (\"Registration Successful, your account has been sent for approval, and will be activated within 24 hours. \");</script>";
echo "<meta http-equiv='refresh' content='0'>";
}
}
?>
<!-- Registration form -->
<form name="register" id="register" method="post" action="register1.php">
<input type='hidden' name='register' value='yes'>
<table border = '0'>
<tr><td><strong> First Name:</strong></td><td><input type = "text" name = "first_name" size="30" value=""></td></tr>
<tr><td><strong> Last Name:</strong></td><td><input type = "text" name = "last_name" size="30" value=""></td></tr>
<tr><td><strong> Username:</strong></td><td> <input type = "text" name = "username" size="30" value=""> </td></tr>
<tr><td><strong> Email: </strong></td><td><input type = "text" name = "email" size="30" value=""> </td></tr>
<tr><td><strong> Password:</strong></td><td><input type = "password" name = "password" size="30" value=""> </td></tr>
<tr><td> <strong>Verify Password:</strong></td><td><input type = "password" name = "password2" size="30" value=""> </td></tr>
</table>
<p>
<input type ="button" value="Register" input class='button' onclick="verifyForm()"/>
</p>
</form>
Your conditional statements DO print the desired result but not stopping the program from executing.
For example:
$i = 1;
if ($i > 0) {
echo 'I want to stop the program, you have entered invalid $i';
}
Register();
However, you will print the message, but Register() will execute too. Because if() block does not necessarily means stop from execution.
You either have to use die(), exit or return in functions/methods
E.g.:
$i = 1;
if ($i > 0) {
die('I want to stop the program, you have entered invalid $i');
}
Register();
I have a registration form. In the database, the username and email are unique index. When the form submits and username or email are already present in the database, the values are not inserted. I want to notify the user that the values were not inserted. How can i do this?
HTML
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
*Sweet And Short *
First check that username or email is exist or not using select query if resulting is 0 (it means not exists), Insert query will run ahead
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
The query method would return true or false, depending on if the row has been inserted or not.
Try the following Code
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}
Below is my code for register.php on my website. This code allows the user to register for my website, creating a MySQL entry for username, email, password, etc. on clicking the submit button.
The button is named "reg" and uses a $_POST. Upon clicking the submit button the PHP code runs through multiple if statements to ensure the information the user entered is valid and does not preexist.
If a user exists, or an error is made in submission it sets PHP variable $errormessage and is supposed to echo it out. Right now, my SUBMIT button does not act like it is being pressed. No error messages, no SQL row is inserted, nothing.
<?php
if( $_POST['reg']){
/* Make sure values are correct and valid */
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['password'];
$getrepass = $_POST['retypepassword'];
/* Check to see if username entererd */
if($getuser){
/* Check to see if email entererd */
if($getemail){
/* Check to see if password entererd */
if($getpass){
/* Check to see if retyped password entererd */
if($getrepass){
/* Check to see if passwords are the EXACT same */
if($getpass === $getrepass){
/* Check to see if VALID email is entered */
if( (strlen($getemail) >= 7) &&
(strstr($getemail, "#")) &&
(strstr($getemail, ".")) ){
/* Email is valid mysql query */
require ("./connect.php");
$query = mysql_query("SELECT * FROM users WHERE username ='$getuser'");
/* If mysql returns zero, the user does not exist. */
$numrows = mysql_num_rows($query);
/* Check if email exists */
if($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email ='$getemail'");
$numrows = mysql_num_rows($query);
if($numrows == 0){
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '0', '$code', '$date')");
$query = mysql_query ("SELECT ALL * FROM users WHERE username = '$getuser'");
$numrows = mysql_num_rows($query);
/* Check to make user was generated */
if($numrows == 1){
$site = "http://www.midnightnachos.com/gs";
$webmaster = "universitydb#gmail.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks for registering. Click the link below to activate your account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You must activate your account to login.";
if (mail($getemail, $subject, $message, $headers)){
$errormessage = "You have been registered. You must activate your account from the activation link sent to your email.";
echo $form;
$getuser = "";
$getpass = "";
}
else
echo "An error has occured. Your activation email was not sent.";
}
else
$errormessage = "An error has occurred. Account not created.";
}
else
$errormessage = "Email address already in use.";
}
else
$errormessage = "Username already exists.";
mysql_close;
}
else
$errormessage = "You did not enter a valid email.";
}
else
$errormessage = "Your passwords did not match.";
}
else
$errormessage = "You must retype your password.";
}
else
$errormessage = "You must enter your password.";
}
else
$errormessage = "You must enter an email to register.";
}
else
$errormessage = "You must enter a username to register.";
echo $form;
}
$form = "
<div class='splash'>
<h1>Register for Game Swap</h1>
<p>Register for Game Swap to browse what games other local
users have added to their library. Propose trades,
chat, and meet to swap games. Your email address
will only be used to notify you when someone has
sent a trade offer. No newsletters, advertisements or
updates will be sent by us. We will also never sell
your contact information to third parties.</p>
<br />
<p align='center'>Fill out the form below to get started</p>
<br />
<form align='center' action='./register.php' method='POST'>
<input type='text' name='user' value='$getuser' class='box' size='30' placeholder='Username' /><br />
<input type='password' name='password' class='box' size='30' placeholder='Password' /><br />
<input type='password' name='retypepassword' class='box' size='30' placeholder='Retype Password' /><br />
<input type='text' name ='email' value='$getemail' class='box' size='30' placeholder='Email Address' /><br />
<input type='button' name='reg' class='loginbutton' value='Register' /><br />
</form>
</div>
<br/> $errormessage";
echo $form;
?>
</body>
</html>
I think you mixed up the button's type attribute, i.e. it's not button, but submit.
So, I guess you have a normal text input field, but your CSS is cheating your eyes. Try writing into it :)
To submit forms via buttons you can use:
<input type="submit" name="reg" value="Register!"/>
<button name="reg" value="1-or-anything">Register!</button>
And as for a possible different way of coding (getting all the validation errors at once):
$error_list = array();
if ($condition1) $error_list[] = 'My Error message 1';
if ($condition2) $error_list[] = 'My Error message 2';
if ($condition3) $error_list[] = 'My Error message 3';
...
if (empty($error_list)) the_fun_part();
else {
foreach($error_list as $msg)
echo "{$msg}<br/>";
}
This registration form worked like a charm for months. I have changed nothing. Now, it gets through all the conditionals of duplicate name, email, and the password check, and then fails to INSERT mysql and returns the "An error has occurred. Your account was not created." I don't see why. Has syntax changed or what?
<div id="backdrop"></div>
<div id="register">
<img src="http://www.staketheclaim.com/wp-content/themes/retlehs-roots-c526a84/dropbox/2012/rotate/header<?php echo(rand(1,4)); ?>.png" style="margin-left: -25px;margin-top: -20px;" />
<div id="regi" style="width:400px;float: right;">
<?php
if ($username && $userid) {
echo "<div id='log-re' style='margin-left: 6px;width: 413px;'><h2>You must logout to register a new account. Not your Account?</h2>" . "<br /><br /><div id='cta'><a href='http://www.staketheclaim.com/logout/' class='button' style='padding-left: 36px;font-size: 24px;top: 2px;right: -160px;'>Logout Now</a></div></div>";
}
else {
if ($_POST['registerbtn']) {
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$password = $_POST['pass'];
$getretypepass = $_POST['retypepass'];
if ($getuser) {
if(strpos($getuser, ' ') > 0 == false ){
if ($getemail) {
if ($password) {
if ($getretypepass) {
if ( $password === $getretypepass) {
if ( (strlen($getemail) >= 7) && (strstr($getemail, "#")) && (strstr($getemail, "."))){
require("base.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("ss3verds4g".$password."ss357rd5sg"));
$date = date("F d Y");
$code = md5(rand());
$bio = "Bio";
$location = "Location";
mysql_query("INSERT INTO users VALUES (
'','$getuser', '$password', '$getemail', '0', '$code', '$date', '$bio', '$location', '1'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1){
$site = "http://www.staketheclaim.com";
$webmaster = "noreply <noreply#staketheclaim.com>";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks for registering. Click the link below to activate your account.\n";
$message .= "$site/activate/?user=$getuser&code=$code\n";
$message .= "You must activate your account to login.";
if (mail($getemail, $subject, $message, $headers )) {
$errormsg = "You have been registered. You must activate your account from the activition link send to <b>$getemail</b>.";
$getuser = "";
$getemail = "";
}
else
else
$errormsg ="An error has occured. Your account was not created.";
}
else
$errormsg ="Their is already a user with that email.";
}
else
$errormsg ="Their is already a user with that username.";
mysql_close;
}
else
$errormsg = "You must enter a valid email address to register.";
}
else
$errormsg = "Your passwords did not match.";
} else
$errormsg = "You must retype you password to register.";
} else
$errormsg = "You must enter a password to register.";
} else
$errormsg = "You must enter you email to register.";
} else
$errormsg = "Your username cannot have any spaces.<br />";
} else
$errormsg = "You must enter a username to register.<br />";
} $form = "<form action='' method='post' style='margin-top:-20px;'>
<h2>Sign up for StakeTheClaimâ„¢.<br /> It's free!</h2>
<br />
<font color='red'>$errormsg</font>
<br />
<br />
Username:
<br />
<input type='text' name='user' value='$getuser' style='' />
<br />
<br />
Email:
<br />
<input type='text' name='email' value='$getemail' />
<br />
<br />
Password:
<br />
<input type='password' name='pass' value='' />
<br />
<br />
Re-Password:
<br />
<input type='password' name='retypepass' value='' />
<br />
<input type='submit' name='registerbtn' value='Register' />
</form>";
echo $form;
}
?></div></div>
It is possible this is a mysql data type issue (well, limit really). You say it fails on update but I'm only seeing an insert statement.
What are the column types on the table users where the insert is being run?
Basically, if you reach the limit of the column type, the insert will fail. This would be consistent with what you have said.
Edit: Also, PHP is depreciating mysql_* calls. Shift to either mysqli_* or another alternative like PDO. The shift to mysqli for this code would be easy, but then your code needs for a full review, it is full of issues. What version of PHP are you running?