How to validate form field in php - php

I have a registration form that has some required field. i want to check if those required fields are filled and if they are filled correctly before i insert in my database.
One of the required field is email, i also want to check if the email entered is a valid email.
My code is below.
Thanks in advance for your help, i really appreciate it.
<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings
$firstname = mysql_real_escape_string($_POST['firstname']);
$middlename = mysql_real_escape_string($_POST['middlename']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$sex = mysql_real_escape_string($_POST['sex']);
$address = mysql_real_escape_string($_POST['address']);
$employer = mysql_real_escape_string($_POST['employer']);
$posincom = mysql_real_escape_string($_POST['posincom']);
$states = mysql_real_escape_string($_POST['states']);
$agerange = mysql_real_escape_string($_POST['agerange']);
$income = mysql_real_escape_string($_POST['income']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
?>

<?php
include 'config.php';
$tbl_name="citizens"; // Table name
$required = array('email');
$errors = array();
foreach($required as $required_fieldname){
if(!isset($_POST[$required_fieldname]) || empty($_POST[$required_fieldname])){
$errors[] = 'Sorry!!! Could Not Register You. All a* fields must be field.';
break;
}
}
if(isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$errors[] = "That is not a valid email address.";
}
if(count($errors) == 0){
// Get values from form and formatting them as SQL strings
$firstname = mysql_real_escape_string($_POST['firstname']);
$middlename = mysql_real_escape_string($_POST['middlename']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$sex = mysql_real_escape_string($_POST['sex']);
$address = mysql_real_escape_string($_POST['address']);
$employer = mysql_real_escape_string($_POST['employer']);
$posincom = mysql_real_escape_string($_POST['posincom']);
$states = mysql_real_escape_string($_POST['states']);
$agerange = mysql_real_escape_string($_POST['agerange']);
$income = mysql_real_escape_string($_POST['income']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result= mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successfully Registered";
}else {
echo "A technical error has occured.";
}
}
else{
echo '<strong>ERRORS!</strong><br>';
foreach($errors as $error){
echo $error . '<br>';
}
}
?>

you should validate form before submitting at client side using JavaScript, and alert to user if not filled correctly. Once validated allow it to submit .
In other case it is overhead to validate at server and than again send response to user at client end.

<?php
include 'config.php';
$tbl_name="citizens"; // Table name
// Get values from form and formatting them as SQL strings
//your other fields ...
$email = mysql_real_escape_string($_POST['email']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors = 1;
echo "Please enter a correct email address";
}
//similar approach can be used for other fields..
// this is one of the simplest validating approach
if($errors == 0){
// Insert data into mysql
$sql="INSERT INTO `$tbl_name` (firstname, middlename, lastname, sex, address, employer, position_in_company, states, age_range, local_govt_area, email, phone) VALUES('$firstname', '$middlename', '$lastname', '$sex', '$address', '$employer', '$posincom', '$states', '$agerange', '$income', '$email', '$phone')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "You Have Successful Registered";
}else {
echo "Sorry!!! Could Not Register You. All a* fields must be field.";
}
}
?>

For email you can use this (or similar) functions from https://stackoverflow.com/questions/3314493/check-for-valid-email-address to validate email
function isValidEmail($email){
return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
}
Or
function isValidEmail( $email ){
return filter_var( $email, FILTER_VALIDATE_EMAIL );
}
For the rest, you can use the following
<?php
$error = '';
//put chosen function here
function isValidEmail( $email ){
return filter_var( $email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$firstname = mysql_real_escape_string($_POST['firstname']);
if(!$firstname){ $error .= "First name is required<br />"; }
//repeat for each field
$email = mysql_real_escape_string($_POST['email']);
if(!isValidEmail($email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
}
else{
//display $error however you want e.g....
echo "<div class=\"error\">$error</div>";
}
?>

1.) you can use PHP_FILTER for validation.
2.) you can proper check( variable is null or not) before insert the data if variable is null the display error msg otherwish insert..

Related

phpMyAdmin database is connected but not inserting data

I'm creating a Wedding Planning Web Application. My Database is connected but no data is being inserted nor am I receiving any error messages when trying to register a user.
I'm being directed straight to the linked Login page. I've tried to match the date formatting (User input as dd/mm/yyyy and being stored as yyyy/mm/dd) from php and MySQL but not sure if it's working/ if it is the issue.
I've been trying to figure out a solution for hours and I'm under pressure to solve it so I can complete my dissertation.
<?php
//Starts the session
session_start();
require_once 'DBConnect.php';
$firstname = "";
$lastname = "";
$email_address = "";
$phone_num = "";
$acc_password = "";
$weddingdate = "";
// REGISTER USER
if (isset($_POST['btn-Register']))
{
// receive all input values from the form
$firstname = mysqli_real_escape_string($DBcon, $_POST['firstname']);
$lastname = mysqli_real_escape_string($DBcon, $_POST['lastname']);
$email_address = mysqli_real_escape_string($DBcon,
$_POST['email_address']);
$phone_num = mysqli_real_escape_string($DBcon, $_POST['phone_num']);
$acc_password = mysqli_real_escape_string($DBcon,
$_POST['acc_password']);
$weddingdate = mysqli_real_escape_string($DBcon,
$_POST['weddingdate']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
// phone_num and weddingdate can be NULL
if (empty($firstname)) { array_push($errors, "First Name is
required"); }
if (empty($lastname)) { array_push($errors, "Last Name is
required"); }
if (empty($email_address)) { array_push($errors, "Email is
required"); }
if (empty($acc_password)) { array_push($errors, "Password is
required"); }
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM customer WHERE email_address =
'$email_address' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
//if user exists
if ($user['email_address'] === $email_address)
{
array_push($errors, "User already exists");
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0)
{
//encrypt the password before saving in the database
$acc_password = md5($acc_password);
$query = "INSERT INTO customer (firstname, lastname,
email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname' '$email_address',
'$phone_num', '$acc_password', '$weddingdate')";
mysqli_query($DBcon, $query);
$_SESSION['email_address'] = $email_address;
$_SESSION['success'] = "You are now Registered";
header('location: Login.php');
}
//This should format the date with phpMyAdmin
$weddingdate = date('Y-m-d H:i', strtotime($_POST["weddingdate"]));
// LOGIN USER
if (isset($_POST['btn-Login']))
{
$email_address = mysqli_real_escape_string($DBcon,
$_POST['email_address']);
$acc_password = mysqli_real_escape_string($DBcon,
$_POST['acc_password']);
if (empty($email_address))
{
array_push($errors, "Email Address is required");
}
if (empty($acc_password))
{
array_push($errors, "Password is required");
}
if (count($errors) == 0)
{
$acc_password = md5($acc_password);
$query = "SELECT * FROM customer WHERE
email_address='$email_address' AND
acc_password='$acc_password'";
$results = mysqli_query($DBcon, $query);
if (mysqli_num_rows($results) == 1)
{
$_SESSION['email_address'] = $email_address;
$_SESSION['success'] = "You are now logged in";
header('location: Main.php');
}else
{
array_push($errors, "Wrong username/password
combination");
}
}
}
}
?>
There is syntax error in insert query line.
$query = "INSERT INTO customer (firstname, lastname, email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname', '$email_address', '$phone_num', '$acc_password', '$weddingdate')";
One Comma , is missing after '$lastname'
The issue is probably that the variables aren't being taken as their values. You need to escape the sequence before you can add the variables. So, instead of having
$query = "INSERT INTO customer (firstname, lastname,
email_address, phone_num, acc_password, weddingdate)
VALUES('$firstname', '$lastname', '$email_address',
'$phone_num', '$acc_password', '$weddingdate')";
You need to do this
$query = "INSERT INTO customer (firstname, lastname, email_address,
phone_num, acc_password, weddingdate) VALUES(
'" . $firstname . "', '" . $lastname . "',
'" . $email_address . "', '" . $phone_num . "',
'" . $acc_password . "', '" . $weddingdate . "')";
This should fix your problem, but as a few of the other commenters have mentioned, this may leave you open to SQL injection. You should be using prepared statements to protect yourself from those vulnerabilities.

Register page wont insert data to database

Not sure why but when I hit submit on register form it wont insert data into database, it performs the last else statement at the bottom by redirecting to signup success page which confuses me. I had it working but I did something and I cant figure out what is wrong..
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$email = $_POST['email'];
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Display1 = $_POST['Display1'];
$Display2 = $_POST['Display2'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if(empty($username) or empty($password) or empty($email) or empty($Fname) or empty($Lname) or empty($Display1)) {
echo '<p>Fields Empty!</p>';
} else if(mysql_num_rows($query) > 0){
$query = mysql_query("SELECT * FROM users WHERE username ='$username' AND password ='$password'");
echo'<p>Username or Password Already Exists!</p>';
} else {
mysql_query("INSERT INTO users VALUES('', '$username', '$password', '2', 'a', '$Fname', '$Lname', '$email', '$Display1', '$Display2')");
$subject = "Membership Confirmation";
$message = "Hello, You have registered an account on Joepepjoepep.com";
$from = "From: joepep235#gmail.com";
header("location:signuppayment.php");
mail($email, $subject, $message, $from);
}
}
?>
Create a unique key for your username field in the table definition.
Then a username can only be once in the table and a second insert query with the same username will fail with a specific error code. (and you avoid the race condition because of your multiple queries)
You can check for that error code and then display the "username already in use" error message.
Try this:
You forgot to put the rows you need to be inserted in your database.
mysql_query("INSERT INTO users VALUES('', '$username', '$password', '2', 'a', '$Fname', '$Lname', '$email', '$Display1', '$Display2')");
Change this into something like this:
mysql_query("INSERT INTO users(id, username, password, Display1, Display2, email, Fname, Lname, user_level, type) VALUES ('', '$username', '$password', '$Display1', '$Display2', '$email', '$Fname', '$Lname', '2', 'a')");
and so apply this in your code:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$email = $_POST['email'];
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Display1 = $_POST['Display1'];
$Display2 = $_POST['Display2'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if((empty($username)) || (empty($password)) || (empty($email)) || (empty($Fname)) || (empty($Lname)) || (empty($Display1))) {
echo '<p>Fields Empty!</p>';
} else if(mysql_num_rows($query) > 0){
$query = mysql_query("SELECT * FROM users WHERE username ='$username' AND password ='$password'");
echo'<p>Username or Password Already Exists!</p>';
} else {
mysql_query("INSERT INTO users(id, username, password, Display1, Display2, email, Fname, Lname, user_level, type) VALUES ('', '$username', '$password', '$Display1', '$Display2', '$email', '$Fname', '$Lname', '2', 'a')");
$subject = "Membership Confirmation";
$message = "Hello, You have registered an account on Joepepjoepep.com";
$from = "From: joepep235#gmail.com";
header("location:signuppayment.php");
mail($email, $subject, $message, $from);
}
}
?>
Hope this helps.

unknown column 'email' in where clause

I have problem with this code. It gives me 'Unknown column 'email' in where clause.
I tried almost everything, but I don't know what is the problem. I am beginner so please be gentle :)
Any ideas how to solve it?
Thanks a lot
session_start();
include('connect.php');
if(isset($_POST['submit']))
//when isn't username in form
if($_POST['firstname'] == '')
{
$_SESSION['error']['firstname'] = 'First name is required';
}
if($_POST['surname'] == '')
{
$_SESSION['error']['surname'] = 'Surname is required';
}
//when email isn't in form
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = 'Email is required';
}
//check if is email in correct format
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//email is in correct format and exist?
$email = $_POST['email'];
$sql1 = "SELECT * FROM users WHERE email = '$email'";
$result1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
if(mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = 'Email is already used';
}
}
else
//error for wrong format of email
{
$_SESSION['error']['email'] = 'Your email is in wrong format';
}
//when isn't password in form
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = 'Password is required';
}
//when is error -> registration form
/*if(isset($_SESSION['error']))
{
header("Location: index.php");
exit();
}
else
*/
{
$firstname = mysqli_real_escape_string($connect,$_POST['firstname']);
$surname = mysqli_real_escape_string($connect,$_POST['surname']);
$email = $_POST['email'];
$password = mysqli_real_escape_string($connect,$_POST['password']);
$phone_number = mysqli_real_escape_string($connect,$_POST['phone_number']);
$note = mysqli_real_escape_string($connect,$_POST['note']);
$sql2 = "INSERT INTO users (firstname, surname, email, phone_number, note, password) VALUES ('$firstname', '$surname',
'$email', '$phone_number', '$note','$password')";
$result2 = mysqli_query($connect, $sql2) or die('Error: ' .mysqli_error($connect));
the column name email may be wrong or does not exist in the data base use the same column name as defined in the data base

Information not getting submitted to MySQL

I am creating a simple login script using PHP and MySQL, no errors are coming up but for some reason the information submitted is just not being inserted into the database.
The database is named 'test' (Without quotes) and the table 'users' (Also without quotes).
The columns in the table are first_name, last_name, email, pass and registration_date.
Here is the html form:
<form action="script4.php" method="post">
<p>First Name:<input type="text" name="first_name" value="first_name" /></p>
<p>Last Name:<input type="text" name="last_name" value="last_name" /></p>
<p>Email: <input type="text" name="email" value="email" /></p>
<p>Password: <input type="password" name="pass1" value="pass1" /></p>
<p>Confirm Password: <input type="password" name="pass2" value="pass2"/></p>
<input type="submit" name="submit" value="register" />
</form>
and here is script4.php
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
require ('mysql_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();}
if (!empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
if (!empty($_POST['last_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$ln = trim($_POST['last_name']);
}
if (!empty($_POST['email'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$e = trim($_POST['email']);
}
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = "Your passwords do not match.";
} else {
$p = trim($_POST['pass1']);}
}else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users ('first_name', 'last_name', 'email', 'pass', 'registration_date') VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
} }
mysqli_close($dbc);
?>
I know this script is vulnerable to sql injection, it is just a test:)
The data will just not get submitted.
Remove the single quotes from the column names.
You are calling require ('mysql_connect.php') twice.
You had multiple syntax errors.
You were assigning variables but not calling them.
You tried to add $pass to the database instead of $pass1.
I cleaned your code.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$first_name = empty($_POST['first_name']) ? '' : trim($_POST['first_name']);;
$last_name = empty($_POST['last_name']) ? '' : trim($_POST['last_name']);;
$email = empty($_POST['email']) ? '' : trim($_POST['email']);;
$pass1 = empty($_POST['pass1']) ? '' : trim($_POST['pass1']);
$pass2 = $_POST['pass2'];
if (!$first_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$last_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$email) {
$errors[] = "You forgot to enter your first name!";
}
if ($pass1) {
if ($pass1 != $pass2) {
$errors[] = "Your passwords do not match.";
}
} else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass,registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass1'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
}
mysqli_close($dbc);
} else {
foreach ($errors as $error) echo $error . '<br>';
}
}
?>
Also, it will be wise to escape the $_POST data or even better - use a prepared statements as currently, you are volunerable to SQL injection.
Hope this helps!
Remove the ! in all your conditional statements:
if (!empty($_POST['last_name']))
Means "if last_name is NOT empty", because of the !. Which means that your script currently says "error" if the fields are NOT empty. And if the scripts says "error", then in the end it doesn't insert the values in the database.
It doesn't say "we are sorry" too, because this statement is inside your conditional if(empty($errors)). So if $errors is not empty, you directly go to the end of the script without displaying anything, but witout having inserted your values.
So what you should do, for instance, is this:
if (empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
And in the end:
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ($first_name, $last_name, $email, SHA1($pass), NOW());";
if (#mysqli_query ($dbc, $q)) {
echo("Thanks");
} else {
echo mysqli_error($dbc);
echo("We are sorry, there is a problem with the database connection.");
}
} else {
echo("We are sorry, there are errors in the values you entered.");
}
mysqli_close($dbc);
As the others said, be careful because you have to remove one of your require('mysql_connect.php').
Remove the first require ('mysql_connect.php');
and change the following line to something like this because you got wrong syntax for your query and your trigger_error
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query($dbc, $q) or trigger_error('Query Error: ' . mysqli_error($dbc));
Remove the # and change mysql_error to mysqli_error with link otherwise you won't get your error.
if(empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `pass`, `registration_date`) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query ($dbc, $q);
if($r){
echo "Thanks";
}else{
echo "We are sorry, you could not be entered at this time.";
trigger_error('Query Error: ' . mysqli_error($dbc));
}
mysqli_close($dbc);
}
Also you should look into binding parameters so eliminate sql injections.

function sending email twice

I have the following function sending an email twice (and I believe running if($result) twice).
it is called on a separate page :
<?php $User = new User();
$User->ValidReg();
$valid = $User->ValidReg();
if ($valid === false) {
Here is the function in its class:
public function ValidReg() {
if ( !empty($_POST['username'])
&& !empty($_POST['password'])
&& !empty($_POST['email'])
&& !empty($_POST['state'])) {
//valid ?
$valid = true;
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$state = mysql_real_escape_string($_POST['state']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1) {
echo "<div id='shopperlogin1'><p>Sorry, that username is taken.<br /> Please go back and try again.</p></div>";
}
else {
//test
$confirm_code=mysql_real_escape_string(md5(uniqid(rand())));
$sql="INSERT INTO temp_users (
confirm_code, Username, Password,
EmailAddress, FirstName, LastName, State)
VALUES (
'$confirm_code', '$username', '$password',
'$email', '$firstname', '$lastname', '$state')";
$result=mysql_query($sql)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
// if suceesfully inserted data into database, send confirmation link to email
if ($result) {
// send e-mail to ...
$to=$email;
// Your subject
$subject="Your confirmation link here";
// From
$header="blahblah#blahbalh.com";
// Your message
$message="Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.employeediscounted.com/secret/login.php?passkey=$confirm_code";
// send email
$sentmail = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "<div id='emailmsg'>Not found your email in our database.</div>";
}
// if your email succesfully sent
if($sentmail){
echo "<div id='emailmsg'>Your Confirmation link Has Been Sent To Your Email Address.</div>";
}
else {
echo "<div id='emailmsg'>Cannot send Confirmation link to your e-mail address.</div>";
}
}
}
else {
$valid = false;
}
return $valid;
}
Either I'm missing something, or you're simply calling the function twice:
$User->ValidReg();
$valid = $User->ValidReg();
So, yes, you will send two emails!
(Were you expecting the second call to fail because the user already exists? It won't because you're using two different tables, users vs. temp_users.)

Categories