where condition in select query - php

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

Related

MySQL `UPDATE` statement with an `IF` condition

I'm trying to create a MySQL UPDATE statement with an IF condition.
I would like to update the user's particulars if the email and username are not duplicate or found in database.
I'm stuck with this code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Check Email in Database
$query = mysqli_query($con,"SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_fetch_object($query);
if (strtolower(trim($query->email)) == strtolower(trim($em))
|| strtolower(trim($user->username)) == strtolower(trim($user))
) {
//next to condition username
} else {
$data_email = mysqli_query($con,"select email from user where em='".$em."'");
$total_email = mysqli_num_rows($data_email);
if($total_email > 0) {
echo "Email Not Available";
} else {
//next to condition username
}
}
//Check Username in Database
$data_us_user = mysqli_query($con,"select username from user where id_user='".$id."'");
$us_user = mysqli_fetch_object($data_us_user);
if (strtolower(trim($us_user->username))==strtolower(trim($user))) {
//next to query update
} else {
$data_username = mysqli_query($con,"select username from user where username='".$em."'");
$total_username = mysqli_num_rows($data_username);
if($total_username > 0) {
echo "Username Not Available";
} else {
//next to query update
}
} else {
//Finally Query Update
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
The following PHP script will check for
IF the user's updated email and updated username are the same
IF the user's new email and username is already in use by another user
IF both conditions are not met, the user's details will be updated
PHP code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Getting user' details in database
$query = mysqli_query($con, "SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_query($query);
//Query to find if email exists
$query2 = mysqli_query($con,"SELECT `email` from `user` WHERE em = '$em'");
$result2 = mysqli_num_rows($query2);
//Query to find if username exists
$query3 = mysqli_query($con,"SELECT `email` from `user` WHERE id_user = '$user");
$result3 = mysqli_num_rows($query3);
while ($row = mysqli_fetch_row($result)){
list($userfromdb, $emfromdb) = $row;
}
if (strtolower(trim($userfromdb)) == strtolower(trim($user))){
//will return true if user's username is the same before updating
echo 'Username cannot be the same!';
} else if(strtolower(trim($emfromdb)) == strtolower(trim($em))) {
//will return true if user's email is the same before updating
echo 'Email cannot be the same!';
} else if($result2 > 0) {
echo "Email Not Available";
} else if($result3 > 0) {
echo "Username Not Available";
} else {
//Finally Query Update
mysqli_query($con, "UPDATE `user` set username = '$user',em = '$em' WHERE id_user = '$id'");
//check if row updated successfully
$result4 = mysqli_affected_rows($con);
if ($result4 > 0) {
echo "Updated details successfully";
} else {
echo "An error occurred while updated details.";
}
}
?>
This should work, thanks!
If specifying column related message is not the concern,
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
$data_us_em = mysqli_query($con,"select count(email) as count from user where id_user='".$id."' OR em='".$em."' OR username='".$em."'");
if($data_us_em)
{
$us_em = mysqli_fetch_assoc($data_us_em);
$count=$us_em['count'];
if($count)
{
echo 'Can not update';
}else
{
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
}
?>
$data_user= mysqli_query($con,"select email,username from user where id_user='".$id."'");
$userdetail = mysqli_fetch_object($data_user);
if (strtolower(trim($userdetail->email))==strtolower(trim($em)) || strtolower(trim($userdetail->username))==strtolower(trim($user)))
{
return "error message";
}else{
//your update method here
}

getting my sql insert query to work within a function

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.

My MySQL query and while loop and SESSIONS aren't working 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.

ban and user activation system but I have some problems on the login script

I'm new to php. I have a login system, and now I'm trying to implement a ban and user activation system but I have some problems on the login script. Here is the code from my script:
<?php
$query = "SELECT id, username, password, salt, email, firstname, lastname, active, banned FROM users WHERE username = :username ";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
$login_ok = false;
$login_match = false;
$login_active = false;
$login_banned = false;
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
if($check_password === $row['password'])
{
$login_match = true;
}
if($row['active'] == 1) {
$login_active = true;
}
if($row['banned'] == 1) {
$login_banned = true;
}
if($login_match && $login_active && !$login_banned) {
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: index.php");
die("Redirecting...");
}
else
{
if(!$login_match) { echo "Wrong username/pasword.";}
if(!$login_active) { echo "Account not activated, check your email";}
if($login_banned) { echo "Your account is banned";}
}
?>
In my Database I have 2 columns active and banned, where 0 means that account is activated and not banned, and 1 if account is not activate or is banned.
How can I display different messages to the user? If a user will enter a wrong username or password, he will get all three messages from the final else {}. I want to display messages to the user like this:
If username or password is wrong, display only Wrong username/pasword. and ignore $login_active $login_banned.
If username/password is ok, but account not activated, Account not activated, check your email. and ignore the $login_banned switch.
If username/password is ok, but account is banned display Your account is banned and ignore the $login_active switch.
I'm sorry if I wrote too much, I hope I explained right.
Change this:
if(!$login_match) { echo "Wrong username/pasword.";}
if(!$login_active) { echo "Account not activated, check your email";}
if($login_banned) { echo "Your account is banned";}
To this:
<?php
if ($login_banned == true) {
echo "Your account is banned";
} else if ($login_match != true) {
echo "Wrong username/password.";
} else if ($login_active != true) {
echo "Account not activated, check your email";
}
?>
I hope it does what you want.
Below are options you could still use:
//PICK OPTIONS DEPENDING ON YOUR PREFERENCE AND MESSAGE PRIORITIES
//option 1
if ($login_match != true) {
echo "Wrong username/pasword.";
} else if ($login_banned != true) {
echo "Your account is banned";
} else if ($login_active != true) {
echo "Account not activated, check your email";
}
//option 2
if ($login_match != true) {
echo "Wrong username/pasword.";
} else if ($login_active != true) {
echo "Account not activated, check your email";
} else if ($login_banned != true) {
echo "Your account is banned";
}
//option 3
if ($login_banned == true) {
echo "Your account is banned";
} else if ($login_match != true) {
echo "Wrong username/password.";
} else if ($login_active != true) {
echo "Account not activated, check your email";
}

PHP code show still with error even if all input are correct. What's wrong with my code?

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

Categories