I have a form that passes input data to a processing page. This processing form then checks whether the email and user name already exists in the database. If they do, an error is reported, the function I am having difficulty with is, if the error reports nothing then go and execute the sql insert query otherwise echo the error. I can get most of it to work except the insert data to database. Can anyone help me see the error in my code please ?
Processing page :
<?php
session_start();
list($username,$email,$clubname, $hash) = $_SESSION['data'];
unset($_SESSION['data']);
include_once 'db_connect.php';
$usernameErr = $emailErr = "";
$password = $hash;
$databaseErr = 'cannot connect to database';
$query1 = mysqli_query($mysqli, "SELECT * FROM members WHERE email='".$email."'");
if(mysqli_num_rows($query1) > 0){
// echo 'email already exists';
$usernameErr = "username already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query1))
{
die('Error: ' . mysqli_error($mysqli));
}
}
$query2 = mysqli_query($mysqli, "SELECT * FROM members WHERE username='".$username."'");
if(mysqli_num_rows($query2) > 0){
// echo 'username already exists';
$emailErr = "email already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query2))
{
die('Error: ' . mysqli_error($mysqli));
}
}
if ($usernameErr == "" && $emailErr == "" ) {
$sql = mysqli_query($mysqli, "INSERT INTO members (username, email, password, clubname) VALUES ('$username', '$email', '$password', '$clubname')");
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
}
else {
echo $usernameErr.'<br/><br/>';
echo $emailErr.'<br/><br/>';
}
I came up with this, a simple skeleton, just edit to suit you. Don't forget to hash the password parameter.
function emailEmailExists($emall) {
if(mysqli_num_rows($email) >= 1) {
return 1;
} else {
return 0;
}
}
function usernameExists($username) {
if(mysqli_num_rows($username) >= 1) {
return 1;
} else {
return 0;
}
}
function insertUser($username, $password, $email, $otherField, $otherField, ) {
if(checkEmailExists($email) == 1) {
echo 'Email in use!';
} else if(usernameExists($username) == 1){
echo 'Username in use!';
} else {
$insertUser = mysqli_query($yourQuery);
if($insertUser) {
echo 'User created!';
} else {
// Give error.
}
}
}
Edit
How do you create you DB connection, remove your credentials and please show.
Related
This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' 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 username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie
I have to check both the user name and the email if any of the two already exist,
When I add OR in where condition It is always going in IF condition.
Code:
$fetch_user=mysql_query("SELECT userid FROM users WHERE username ='".$username."' OR email='".$email."'") or die(mysql_error());
if(mysql_num_rows($fetch_user))
{
echo '<font color="red">The nickname <strong>'.$username.''.$email.'</strong>'.' is already in use.</font>';
}
else
{
$query = mysql_query("insert into users values ('','$username','$email','$password','','$roll')") or die(mysql_error());
if($query)
{
echo 'Successfully Inserted';
}
else
{
echo 'Insertion Faild';
}
}
Thanks for any help!
I do not see any thing wrong in the code. However i can only see the logic is incorrect. If username or email already exists, you are showing a message that nickname username and email already in use. It may be possible that only username is already in use but not the email and vice versa. So you need to show proper message to the user which one is taken and which one not.
<?php
$userNameTaken = false;
$emailTaken = false;
//check if username exists
$checkUsername = mysql_query("SELECT userid FROM users WHERE username ='".$username."'") or die(mysql_error());
if(mysql_num_rows($checkUsername))
{
$userNameTaken = true;
}
//check if email exists
$checkEmail = mysql_query("SELECT userid FROM users WHERE email ='".$email."'") or die(mysql_error());
if(mysql_num_rows($checkEmail))
{
$emailTaken = true;
}
if($userNameTaken || $emailTaken) //if any of username or email taken
{
if($userNameTaken && $emailTaken) //username and email both taken
{
echo '<font color="red">The username <strong>'.$username.'</strong> and email <strong>'.$email.'</strong> already in use.</font>';
}
else if($userNameTaken && !$emailTaken) //only username taken
{
echo '<font color="red">The username <strong>'.$username.'</strong> is already in use.</font>';
}
else if(!$userNameTaken && $emailTaken) //only email taken
{
echo '<font color="red">The email <strong>'.$email.'</strong> is already in use.</font>';
}
}
else
{
$query = mysql_query("insert into users values ('','$username','$email','$password','','$roll')") or die(mysql_error());
if($query)
{
echo 'Successfully Inserted';
}
else
{
echo 'Insertion Faild';
}
}
?>
Only change condition
$fetch_user=mysql_query("SELECT userid FROM users WHERE username ='".$username."' OR email='".$email."'") or die(mysql_error());
$num = mysql_num_rows($fetch_user);
if($num > 1)
{
echo '<font color="red">The nickname <strong>'.$username.''.$email.'</strong>'.' is already in use.</font>';
}
else
{
$query = mysql_query("insert into users values ('','$username','$email','$password','','$roll')") or die(mysql_error());
if($query)
{
echo 'Successfully Inserted';
}
else
{
echo 'Insertion Faild';
}
}
You are not validating the result from teh sql query .
the following code will work
$fetch_user=mysql_query("SELECT userid FROM users WHERE username ='".$username."' OR email='".$email."'") or die(mysql_error());
if( !$fetch_user)
{
if(mysql_num_rows($fetch_user) > 0 )
{
echo '<font color="red">The nickname <strong>'.$username.''.$email.'</strong>'.' is already in use.</font>';
}
else
{
$query = mysql_query("insert into users values ('','$username','$email','$password','','$roll')") or die(mysql_error());
if($query)
{
echo 'Successfully Inserted';
}
else
{
echo 'Insertion Faild';
}
}
}
else
[
echo 'query failed';
}
Also look the following documentation links so you understand the functionalities better
http://php.net/manual/en/function.mysql-num-rows.php
http://php.net/manual/en/function.mysql-query.php
In my signup up form I automatically log the user in after they submit all their data. After they submit their data to the database, I run a query to grab that data from the database and store it in session variables. The problem is that The while loop only stores the first variable which is the user ID and doesn't store the rest. What I am Doing wrong?
if ($signup) {
//user clicked the register button
if (isset($username, $em, $pass, $pass2, $fn, $ln, $sex, $bd_day, $bd_month, $bd_year)) {
//if all of these have a value
if ($pass == $pass2) {
//if the passwords match
$sql = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE username = '$username'"));
//check if username is already taken
if ($sql < 1) {
//if the username hasn't been taken
$sql2 = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE email = '$em'"));
//check if the email is taken
if ($sql2 < 1) {
//the email hasn't been taken
if (strlen($pass) > 5) {
//password is more than 5 characters
$pass = md5($pass);
//md5 is not secure!!! use something else later
if (strlen($username) > 4) {
//username is bigger than 4 characters
$query = mysqli_query($con, "INSERT INTO users (username, email, first_name, last_name, sex, bd_month, bd_year, bd_day, password, profile_pic, signup_date, activated, cover_photo) VALUES ('$username','$em','$fn', '$ln', '$sex', '$bd_month', '$bd_year', '$bd_day', '$pass', 'profilepic/default.png','$date)','0', 'coverphoto/defaultcover.jpg')") or die(mysqli_error($con));
//insert into db
$sql3 = mysqli_query($con, "SELECT * FROM users WHERE username = '$username' AND email = '$em'") or die(mysqli_error($con));
//select values from db for login
$num = mysqli_num_rows($sql3);
//check how many hits the query gets it should be 1
if ($sql3 == true && $num > 0) {
//check if query was a success and that there is a user with those credentials
while ($row = mysqli_fetch_assoc($sql3))
//log user in
$_SESSION['id'] = $row['id'];
echo $_SESSION['id'] . '<br>';
$_SESSION['un'] = $row['username'];
echo $_SESSION['un']. '<br>';
$_SESSION['fn'] = $row['first_name'];
echo $_SESSION['fn'] . '<br>';
$_SESSION['ln'] = $row['last_name'];
echo $_SESSION['ln'] . '<br>';
$_SESSION['em'] = $row['email'];
echo $_SESSION['em'] . '<br>';
$_SESSION['pp'] = $row['profile_pic'];
echo $_SESSION['pp'] . '<br>';
$_SESSION['signup_date'] = $row['signup_date'];
$_SESSION['active'] = $row['activated'];
setcookie('un', $username, time()+3600*60*24*7*4);
echo "You have been logged in.";
exit();
} else {
echo "An unknown error occurred";
exit();
}
} else {
//username is less than 4 characters
echo "Your username must be larger than 4 characters!";
exit();
}
} else {
//password is less than 5 characters
echo "You password must be more than 5 characters long<br />";
exit();
}
} else {
//email is already taken
echo "That email has already been taken!";
exit();
}
} else {
//username is already taken
echo "That username is already taken!";
exit();
}
} else {
//the passwords don't match
echo "You passwords don't match";
exit();
}
} else {
//user didn't submit the form
echo "Please fill in all the fields";
exit();
}
} else {
//user didn't click the register button
}
In the end it does echo You have been logged in. Also, I echoed out the values in the session variables for testing but all the return are the <br> not the actual values except for the user ID at the beginning. I don't get any errors either.
Please help me.
while ($row = mysqli_fetch_assoc($sql3))
You forgot to add { and it seems that also } at the end of the loop.
So only the first command takes place in the loop and executed.
Another thing, the "else" after the loop - to which condition is it relate?
Usually I think indents are good, but you took it too far.
Maybe, instead of nesting too many conditions and loops, find another approach.
This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' 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 username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie
I'm making a simple registration system in php however, even if i enter all correct details, it doesn't go to the database, it still echo that withError = 1 even if all entries are correct. Here is my php code.
<?php
if($submit)
{
if ($fullname && $email && $username && $password && $conPassword)
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email))
{
$query1 = "SELECT Email FROM tbl_userAccounts WHERE Email='$email'";
$result1 = mysqli_query($mysqli,$query1) or die(mysqli_error());
if (mysqli_num_rows($result1) < 0)
echo "email is already used. ";
$withError = true;
}
else
{
echo "invalid email address. ";
$withError = true;
}
if (strlen($username) < $charMinimum)
{
echo "minimum of 6 characters for username. ";
$withError = true;
}
else
{
$query2 = "SELECT Username FROM tbl_userAccounts WHERE Username='$username'";
$result2 = mysqli_query($mysqli,$query2) or die(mysqli_error());
if (mysqli_num_rows($result2) < 0)
{
echo "username is already used. ";
$withError = true;
}
}
if($password == $conPassword)
{
echo $withError;
if($withError == false)
{
if (strlen($password) < $charMinimum)
{
echo "minimum of 6 characters for password. ";
$withError = true;
}
else
{
$query3 = "INSERT INTO tbl_userAccounts VALUES ('', '$fullname', '$username', '$password','$date', '$email')";
$result3 = mysqli_query($mysqli,$query3) or die(mysqli_error());
if($result3 && $withError == false)
echo "account has been successfully registered!";
else
echo "failed registration. ";
}
}
}
else
{
echo "passwords do not match. ";
$withError = true;
}
}
}
else
{
echo "fill out all fields. ";
$withError = true;
}
?>
You forgot to wrap the nested IF statement.
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email))
{
$query1 = "SELECT Email FROM tbl_userAccounts WHERE Email='$email'";
$result1 = mysqli_query($mysqli,$query1) or die(mysqli_error());
if (mysqli_num_rows($result1) < 0) {
echo "email is already used. ";
$withError = true;
}
}
if (mysqli_num_rows($result1) < 0)
{
echo "email is already used. ";
$withError = true;
}
You forgot the curly bracket