Can't seem to get thhis script work. Although registration part works fine and data gets inserted but shows error in result page:
Not found your email in our databaseCannot send Confirmation link to your e-mail address
Code:
<?php
$con=mysqli_connect("localhost","","");
if (!$con) { die("Database connection failed: " . mysqli_error());}
$db_select=mysqli_select_db($con, "");
if (!$db_select) { die("Database selection failed: " . mysqli_error());}
if (isset($_POST['register'])) {
$username = mysqli_real_escape_string($con,$_POST['user']);
$password1 = mysqli_real_escape_string($con,$_POST['pass1']);
$password2 = mysqli_real_escape_string($con,$_POST['pass2']);
$name = mysqli_real_escape_string($con,$_POST['name']);
$phone = mysqli_real_escape_string($con,$_POST['phone']);
$email = mysqli_real_escape_string($con,$_POST['email1']);
if(isset($_POST['country'])){ $country = $_POST['country'];}
if(isset($_POST['state'])){ $state = $_POST['state'];}
// Random confirmation code
$confirm_code=md5(uniqid(rand()));
/* Data Insertion & PASSWORD 1 = 2 CHECK */
if($password1==$password2 && !empty($username) && !empty($name) && !empty($phone) && !empty($email) && !empty($country) && !empty($state)){ /* IF PASSWORD1 IS THE SAME WITH PASSWORD2 */
/* INSERT QUERY */
$query = "INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','".$country."','".$state."')";
$result=mysqli_query($con, $query);
if ($result) {
$to = $email;
$subject = "Activate Vacation Rental Link";
// From
$header = "VacationByChoice <enquiry#craigburst.com>";
// message
$message = "Your Confirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="https://craigburst.com/confirmation-link-validation.php?passkey=$confirm_code";
// send email
if(!mail($to, $subject, $message, $header)) {
echo "Cannot send Confirmation link to your e-mail address";
} else {
echo "Your Confirmation link Has Been Sent To Your Email Address.";}
} else {
echo "Not found your email in our database";}}}
?>
Form:
Username:<input type="text" name="user" maxlength="20" class="username" value="<?php echo $username; ?>" /><?php if (!empty($username) === false){echo '<font style="color:#FF0000">* Username</font>';
} else /* duplicate username Validation */ $check_user = ("SELECT username FROM temp_users WHERE username='$username'"); $run = mysqli_query($con,$check_user);
if(mysqli_num_rows($run)>0) {
echo "<font style='color:#FF0000'>* User Exists</font>";} ?>
Choose Password:<input type="password" maxlength="20" name="pass1" value="<?php echo $password1; ?>" /><?php if (!empty($password1) === false){
echo '<font style="color:#FF0000">* Password</font>';} ?>
Repeat Password:<input type="password" maxlength="20" name="pass2" value="<?php echo $password2; ?>" /><?php if (!empty($password2) === false){
echo '<font style="color:#FF0000">* Password</font>';}
elseif($password1!=$password2) { echo '<font style="color:#FF0000">* No Match</font>';} ?>
Full Name:<input type="text" maxlength="50" name="name" value="<?php echo $name; ?>" /><?php if (!empty($name) === false){
echo '<font style="color:#FF0000">* Name</font>';} ?>
Phone:<input type="text" maxlength="20" name="phone" value="<?php echo $phone; ?>" /><?php if (!empty($phone) === false){
echo '<font style="color:#FF0000">* Phone</font>';} ?>
Email:<input type="text" maxlength="50" name="email1" value="<?php echo $email; ?>" /><?php if (!empty($email) === false){
echo '<font style="color:#FF0000">* Email</font>';}
elseif (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
echo '<font style="color:#FF0000">* email';} else
/* duplicate Entry Validation */
$check_email = "SELECT email FROM temp_users WHERE email='$email'";
$run = mysqli_query($con,$check_email);
if(mysqli_num_rows($run)>0) {
echo "<font style='color:#FF0000'>* Email Exists</font><br/>";} ?>
Country:<select id="country" class="style" name="country">
<option>Select</option></select><?php if ($country=['select']){
echo '<font style="color:#FF0000">* Country</font>';} ?>
State/ Province:<select id="state" class="style" name="state"></select><?php if ($state=['select']){
echo '<font style="color:#FF0000">* State</font>';} ?>
<img src="captcha.php" alt="Captcha" /><input type="text" name="vercode" /><?php /* Captcha Validation */
if ($_POST['vercode']!=$_SESSION['vercode'] OR $_SESSION["vercode"]===''){
echo '<font style="color:#FF0000">* code</font>';} ?>
<input type="submit" name="register" value="Sign Up" />
Seeking help on this. Error reporting has been added already.
As my brother from another mother has suggested. You can try this.
Firstly set error reports on to help you debug this further.
ini_set('display_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
That should help you narrow down the cause of your errors.
Now on to your query. As you can see, you're setting your query like this:
$query = mysqli_query($con,"INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','$country','$state')");
$result=mysqli_query($query);
Which means, you're trying to run it like this: mysqli_query(mysqli_query('sql query in here')). That won't work. Try setting it up like this:
$query = "INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','$country','$state')";
$result=mysqli_query($con, $query);
You see how $query is the actual query string and $result runs the query through mysqli_query().
And now keeping in scope, you should do something like this with your code blocks for better management:
if ($result) {
$to = $email;
$subject = "Avtivate Vacation Rental Link";
// From
$header = "VacationByChoice <enquiry#craigburst.com>";
// message
$message = "Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="https://craigburst.com/confirmation-link-validation.php?passkey=$confirm_code";
// send email
if(!mail($to, $subject, $message, $header)) {
echo "Cannot send Confirmation link to your e-mail address";
} else {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
} else {
echo "Not found your email in our database";
}
Notice how we removed the whole $sentmail and check mail directly with the if statement.
Does that help you out?
Notes
Just a few side notes; you have a typo here:
$subject="Avtivate Vacation Rental Link";
should be
$subject="Activate Vacation Rental Link";
and
$message="Your Comfirmation link \r\n";
should be
$message="Your Confirmation link \r\n";
Just had to be picky or Fred will beat me:P
Related
What could be the cause of this? I want it to query the database and send the user message if the specified email exists in the database and flag error otherwise
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include 'includes/config.php';
include 'includes/functions.php';
$email = benny($_POST['email']);
$from = "support#Adsware.com";
$subject = "Password Reset";
$msg = "Hello, you have requested to reset your password";
$to = $email;
if (empty($_POST['email'])) {
echo "<script> alert(\"Please Enter your Email Address.\") </script> ";
}else{
$sql = "SELECT * FROM users WHERE email = $email";
}
if (mysqli_query($con, $sql)) {
if(mail($to, $subject, $msg)){
echo "<script> alert(\"An Email with password reset link has been sent to your email inbox. Please Check it\") </script>";
}else{
echo "<script> alert(\"Email does not Exist\") </script>";
}
}else{
echo "<script> alert(\"Error Encountered\") </script>";
}
}
?>
<form name="recover" action="" method="POST" autocomplete="off">
<label>Username</label>
<input type="email" name="email" placeholder="Enter Your Email">
<input class="login-sub" type="submit" name="submit" value="Reset Password">
</form>
<button id="Login"> Login </button>
But it displays the error:
Warning: mysqli_query(): Empty query in
C:\xampp\htdocs\IT\Adsware.com\recover.php on line 15
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.
Here is my sign_up.php code, I want users to receive a welcome email immediately after hitting the submit button, I have searched so many forums but they are not giving me what i need.
The user successfully signs up, and the details are stored in the database, but i also want to add a welcome mail feature such that the details will me sent to the email immediately after submitting the form
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>
on successful form submission you need to write code for your mail functionality
<?php
if(isset($_POST['submit'])){
$to = $_POST['email'];
$subject = $_POST['name'];
$message = $_POST['message'];
$from = "test#testcom";
$headers = "From:" . $from;
if(mail($to,$subject,$message,$headers))
{
echo "Mail Sent.";
}
else
{
echo "Something went wrong";
}
}
?>
The function for sending mail is mail()
add this mail($email,'Subject','Message_body'); after if(mysql_query('insert into users...
http://www.w3schools.com/php/php_mail.asp
just use the mail function and send the mail as shown below
<?php
$result = mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")');
if($result){
//We dont display the form
$form = false;
//mail function
mail("mail_address#mail.com",'Subject','Message_body');
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
?>
Try it user and admin will get mail
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
$to = "$email";
$subject = "Welcome to";
$message = " Hi $username,<br /><br />
Thank you for signing up with us.<br />
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <test#gmail.com>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($mail)
{
$to = "admin#gmail.com";
$subject = "Following Customer Signed Up";
$message = " $username,Customer is signed up with us,<br /><br />
Customer Details:<br />First Name:$firstname<br/>Last Name:$lastname<br/>Email:$email<br/>
Phone:$phone<br/>Zip Code:$zip<br/>
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <'.$email.'>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
}
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>
Thank you all for your help.
I have successfully added a simple mail function with the help you all have contributed, here is what i did:
I added
mail($email,'Subject','Message_body');
after
if(mysql_query('insert into users(id, username, password, email, avatar, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.time().'")'))
{
//We dont display the form
$form = false;
just like this:
mail("$email",'Welcome To Naijabloom','Dear user, <br /> Welcome to Naijabloom.com, you will start receiving mails from us to keep you updated. Remember to be active in our forums and invite your friends here. Thanks. <br /> Naijanloom Team.', 'info#naijabloom.com');
and it worked for me, thanks
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?
Basically, in the following code:
<?php
$hostname = '';
$username = '';
$password = '';
$dbn = '';
try {
$dbh = mysqli_connect($hostname , $username, $password ,$dbn);
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if (isset($_POST['formsubmitted'])) {
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$email1 = $_POST['email1'];
$password1 = $_POST['password1'];
$dob = $_POST['dob'];
$query_verify_email = "SELECT * FROM User WHERE Email = '$email1'";
$result_verify_email = mysqli_query($dbh, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
//$id= uniqid();
$query_insert_user = "INSERT INTO `User` ( `Name`, `Username`, `Email`, `Password`, `DOB`, `Activation`) VALUES ( '$fullname', '$username', '$email1', '$password1', '$dob', '$activation')";
$result_insert_user = mysqli_query($dbh, $query_insert_user);
if (!$result_insert_user) {
echo 'Query did not work ';
}
if (mysqli_affected_rows($dbh) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= 'http://website' . '/active.php?email=' . urlencode($email1) . "&key=$activation";
mail($email1, 'Registration Confirmation', $message, 'From: a#b.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.
</div>';
}
mysqli_close($dbh);//Close the DB Connection
}// End of the main Submit conditional.
?>
<html>
<head>
</head>
<body>
<form name="f1" action="Main.php" method="post">
<p>Full name: <br/><input class="tb10" type="text" name="fullname" /></p>
<p>Username: <br/><input class="tb10" type="text" id="username" name="username" /><br/>
<p>Email: <br/><input class="tb10" type="text" id="email1" name="email1" /></p>
<p>Re-Enter Email: <br/><input class="tb10" type="text" name="email2" /></p> <br/>
<p>Password: <br/><input class="tb10" type="password" name="password1" /></p>
<p>Re-Enter Password: <br/><input class="tb10" type="password" name="password2" /></p><br/>
<p>Date of Birth: <br/><input class="tb10" type="text" name="dob" /></br><img src="img/calendar1.gif" alt="Calendar" onclick="displayCalendar(document.forms[0].dob,'yyyy/mm/dd',this)"/></p><br/>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Submit" class="button" />
</div>
</form>
</body>
</html>
The problem is I want to show the message that show up in the top (before the html part) in the body part. That means when the user completes the registration, the message will show up instead of the fields in the body section (Name, UserName, Email ,....).
To illustrate it:
If the registration is valid, I want the message:
Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account
Appears in the body part (instead of the fields).
I hope you understand my explanation.
You set a variable, let it be regSuccess, in the php part to either true to false depending on whether user registration was successfull or not
Then in the html part, you checkk for the value of this variable in an if condition and output the corresponding html.
<?php
if($regSuccess == TRUE) {
?>
Thank you message
<?php
}
else
{ ?>
the input fields
<?php
} ?>
you could create a variable to store you error message instead of echo it directly.
And add a 'IF' case in the <body> for validation occur error, echo the error, otherwise print the register form.
Utilize a $_SESSION variable to indicate that the user successfully registered. You will start a session on your page and check if that value is set before doing anything else. If the variable exists, then display the activation message, otherwise provide the registration fields and continue with your existing code.
The reason for utilizing $_SESSION is to persist state information between page requests.
<?php
session_start();
if(isset($_SESSION['registered_email'])){
//Display message indicating user has already registered
echo 'Thank you for registering! A confirmation email has been sent to '. $_SESSION['registered_email'] .' Please click on the Activation Link to Activate your account';
}else{
// The rest of your code
...
// set session variable to indicate the registration was successful
$_SESSION['registered_email'] = $email1;
...
}
?>