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
}
Related
I'm working on a script that checks to see if an email exists in the database barn_users, in order to reset a password. And if the email doesn't exists, the token/code is not generated and stored in the database. Everything works perfectly, until I enter an email that is not in the system. The else statement with the error "Could not find email in the system.", doesn't trigger. What am I doing wrong to not get that?
$sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
$sql_2 = "SELECT * FROM barn_users WHERE email='$email'";
$generate = mysqli_query($conn, $sql_1);
$searchEmail = mysqli_query($conn, $sql_2);
while($row = mysqli_fetch_array($searchEmail)) {
if(mysqli_num_rows($searchEmail) > 0) {
if (mysqli_num_rows($generate) > 1) {
} else if (mysqli_num_rows($generate) < 1) {
$sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
} else {
$sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
}
if ($conn->query($sql) == TRUE) {
echo "Reset password has been emailed to you";
} else {
}
} else {
echo "Could not find email in the system.";
}
}
Thank you #Bleach and #ivanivan for your comments. Both your answers helped out. Here's the working result. Making a variable false outside of the loop, gave me the answer I was looking for.
$sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
$sql_2 = "SELECT * FROM barn_users WHERE email='$email'";
$generate = mysqli_query($conn, $sql_1);
$searchEmail = mysqli_query($conn, $sql_2);
$found = false;
while($row = mysqli_fetch_array($searchEmail)) {
$found = true;
if(mysqli_num_rows($searchEmail) > 0) {
if (mysqli_num_rows($generate) > 1) {
} else if (mysqli_num_rows($generate) < 1) {
$sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
} else {
$sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
}
if ($conn->query($sql) == TRUE) {
echo "Reset password has been emailed to you";
} else {
}
} else {
}
}
if ($found == false) {
echo "Sorry, that email was not found in the system. Please try again.";
}
Can you please help me what is wrong with my code? I cannot seem to find the error. My problem is that the new password is not saving in my database. I cannot log in with my new password.
This is my php code.
<?php
session_start();
$uid = $_SESSION["uid"];
if($uid)
{
//user is logged in
if(isset($_POST["changepwbtn"]))
{
// check fields
$oldpw = $_POST['old_pw'];
$newpw = $_POST['new_pw'];
$renewpw = $_POST['c_npw'];
//check pw db
$sql = "SELECT pazzword FROM customer_info where user_id = '$uid'";
$run_query = mysqli_query($con,$sql);
$row = mysqli_fetch_array($run_query);
$oldpwdb = $row['pazzword'];
//check pw
if($oldpw==$oldpwdb)
{
//check two new pw
if($newpw==$renewpw)
{
$query_change = mysql_query("UPDATE customer_info SET pazzword = '$newpw' WHERE user_id = '$uid'");
session_destroy();
die("Your password has been changed! <a href='index.php'>Return</a>");
}
else
die("New passwords doesn`t match!");
}
else
die("Old password doesn`t match");
}
echo" ";
}
else
die("You need to log in!");
?>
you have to pass the connection object to mysqli_query
$query_change = mysqli_query($con, "UPDATE customer_info SET pazzword = '$newpw' WHERE user_id = '$uid'");
Hello guys I was confused using the if else statement I know it is the basic in conditioning also other languages. Don't know what to do here, I would like that it has an if condition(check) then also inside I want that it has an else if but my problem is I have to else statement which is wrong cause I know that else statement will be use at the end of a condition
Here's my code:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
}
Please help me
You have imbricated your blocks, try this:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
With an indentation, this kind of problem is easily visible.
This can be ok:
if ( //validate the email
filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match('/#.+\./', $email)
) {
$result = mysql_query (
"INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())"
);
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}
}
Try this one :
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email)) {
$result = mysql_query ("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}
I have successfully been able to allow users to invite a friend by sending them an email with a unique invite code,
however I am trying to add to ability to check if it is a valid email address and if the email is already registered in another table 'users' (same database) as it would be a headache for someone who is already registered to receive invite emails.
I have tried to check for a valid email and if it exists by writing this script:
function email_registered($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) ==1) ? true : false;
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
}
if (email_registered($_POST['email']) === true) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use';
}
This was successful for checking emails addresses when registering a user but registering a account was in the same table as already registered account. I am unsure how to use the same script in the invite code as I am trying to check an email in the registered separate table.
Currently it does not check if it is a valid email or if it exists.
The Full PHP:
include 'config.php';
function email_registered($email) {
$email = sanitize($email);
return (mysqli_result(mysqli_query("SELECT mysqli_num_rows()(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) ==1) ? true : false;
}
if(!empty($_POST)){
if(!empty($_POST['email'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
function email_registered($email)
{
if (!empty($email)) {
$ret_val = false;
$query = sprintf(
"SELECT id FROM users WHERE email = '%s'",
mysqli_real_escape_string($email)
);
$result = mysqli_query($query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//email exists
?>
<p>User Exists</p>
<?php
$ret_val = true;
} else {
$query = sprintf(
"SELECT id FROM invites WHERE email = '%s'",
mysqli_real_escape_string($email)
);
$result = mysqli_query($query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//email exists
?>
<p>User Exists</p>
<?php
$ret_val = true;
}
}
return $ret_val;
}
}
else {
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`) VALUES ('$email', '$inviteCode') "); }
//you might want to consider checking more here such as $query == true as it can return other statuses that you may not want
if($query){
include 'userinvite.php';
?>
<p> "Thank you for inviting your friends!"</p>
<?php
}
else{
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
}
}
else {
?>
<p>Please enter an email</p>
<?php
}
}
?>
I am just trying to check if the email is registered in the 'users' table and if the email entered is a valid email.
I think your main question is how to check if an email exists in another table. If that's wrong, let me know and I can update my answer :P Here's a rough draft of a function you should be able to use.
I'm assuming you have these two tables:
Table 1: users
||id||email||name||
Table 2: invites
||id||email||inviter_user_id||
You can use this function to check if the email exists in either table
<?php
/**
* Check if the given email already exists in the DB
*
* #param $email string the email to check
*/
function email_exists($email)
{
if (!empty($email)) {
$ret_val = false;
$query = sprintf(
"SELECT id FROM users WHERE email = '%s'",
mysqli_real_escape_string($email)
);
$result = mysqli_query($query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//email exists
$ret_val = true;
} else {
$query = sprintf(
"SELECT id FROM invites WHERE email = '%s'",
mysqli_real_escape_string($email)
);
$result = mysqli_query($query);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//email exists
$ret_val = true;
}
}
return $ret_val;
}
}
?>
i am unable to get the last 2 echos to work, even if the update query fails it still displays success. If anyone has any suggestions on this code to be improved on any line, please do!
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}
?>
Thanks in advance!
mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error()."update failed");
and use
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last query failed.
use try catch and try to get the error enable error reporting in php also
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;}
try{
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>"; }
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}catch(Exception $e){
print_R($e);
}
}
use or die(mysql_error()) as it will display mysql error if there is an error with your query.
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error());
Try this:
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'");
if(!idfetch){
die(mysql_error());
}
Do the same for all other queries too.
try this, first count the row count value its great 1 then proceed the login process.
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$count= mysql_num_rows($idfetch);
if($count>0){
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
} } ?>
Use
if(mysql_num_rows($updatequery) > 0) {
// success
} else {
// error
}
$updatequery will always be true (not NULL), until there is an error in your query