How to exclude specific selection from query - php

I have this function for email checking in registration form which disables submit button if submitted email is currently in use. So I want to modify that function in profile edit section. I also have profile edit form in profile.php. So when user edits his info withouth touching email input it works fine. But once user clicks and to email field and blurs out the mouse without even editing something it shows "Email Already Taken" error. Which is fine cause function works for registeration form. So when user submits different email I want to check if it's already in db otherwise if he doesn't change anything I want to show nothing and proceed.
I've tried to solve this in back end with this query:
SELECT * FROM users WHERE email = ? AND id != ?
.
.
.
mysqli_stmt_bind_param($stmt, "ss", $email, $uid);
but it doesn't work
Then I tried SELECT * FROM users WHERE email = ?
and looped over selection to detect if there is selection with id = uid. If yes, make result variable 0. But it also doesn't work.
function profEmailCheck(){
$('#email').blur(function(){
var email = $(this).val();
var uid = $('#uid').val();
var update_email_check = '';
$.ajax({
url:'update_email_check.php',
method:"POST",
data:{
update_email_check: update_email_check,
email: email,
uid: uid
},
success:function(data)
{
if(data != 0)
{
$('.email-availability').html('<span class="text-danger">Email Already Taken</span>');
$('#update-prof-btn').attr("disabled", true);
}
else
{
if (email == '')
{
$('.email-availability').html('');
$('#update-prof-btn').attr("disabled", true);
}
else
{
$('.email-availability').html('<span class="text-success">Email Available</span>');
$('#update-prof-btn').attr("disabled", false);
}
}
}
})
});
}
<?php
include('db_connect.php');
if (isset($_POST["update_email_check"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$uid = mysqli_real_escape_string($conn, $_POST["uid"]);
$sql = "SELECT * FROM users WHERE email = ? AND id != ?";
$stmt = mysqli_stmt_init($conn);
$query = mysqli_query($conn, $sql);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Something went wrong :(";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $email, $uid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
$result = mysqli_sql($conn, $sql);
while ($rows = mysqli_fetch_array($query, MYSQLI_ASSOC)){
if($rows['id'] == $uid){
$result = '0';
}
}
echo mysqli_num_rows($result);
}

As far as I understood you want to check email control.
If (exists){
Do something
}
else {
Do something
}
If this is what you want then you should;
$ControlMailQuery = "SELECT * FROM users WHERE email = ?";
$ControlMailQueryResult = mysqli_query($db, $ControlMailQuery);
if(mysqli_num_rows($ControlMailQueryResult) == 1){
//There is a one user who has this email
}
else{
//this is unique e-mail address
}

Related

How to Update SQL Table Where condition is True

PROBLEM: I am trying to UPDATE table data with a "forgot password key" where the email field matches the user's form input on a previous page.
I want to make sure the user's input is sanitized and a match can be found in the database.
ERROR: The code does not update the ForgotKey Field in my Database
Here is my code, error is happening on line 7 where stated in the comment.
$ForgotKeyLength = 9;
$ForgotKeyString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$ForgotKey = substr(str_shuffle($ForgotKeyString), 0, $ForgotKeyLength); //shuffle String, start with 0, 9 characters long
$sql = "UPDATE UserTable SET ForgotKey = ".$ForgotKey." WHERE Email = ? ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../forgot.php?error2"); // THE ERROR HAPPENS HERE, UNABLE TO PREP STATEMENT
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $Email);
mysqli_stmt_execute($stmt); // I believe this line should update the table
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
//success: send user their email from here
$variable = $row['Email'];
}
else {
header("Location: ../forgot.php?error5");
exit();
}
}

Why am I receiving null as a response for an sql column with data in it? (PHP)

I am building a log in system and every other part works perfectly fine except for the portion that cross references the entered password with the password in the database. So when I checked to see if the passwords match I realized that the password from the database is coming back as null. May I ask what is happening?? (There is no issue with the "uidExists" method, it seems to just be in the "loginUser" method).
This is based of of this video https://www.youtube.com/watch?v=gCo6JqGMi30
I believe its around the hour and 40 minute mark he gets to the loginUser function.
function loginUser($conn,$username,$pwd){
$uidExists = uidExists($conn,$username,$username);
if($uidExists === false){
header("location: ../login.php?error=wrongslogin");
exit();
}
else{
echo $pwd;
if(is_null($uidExists["userPwd"])){
echo "Empty bruv";
}
else{
echo $uidExists["userPwd"];
}
}
function uidExists($conn,$username,$email){
$sql = "SELECT * FROM users WHERE userUid = ? OR userEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt,"ss",$username,$email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if(mysqli_fetch_assoc($resultData)){
return $row;
}
else{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
This doesn't look right:
$uidExists = uidExists($conn,$username,$username);
Should this be:
$uidExists = uidExists($conn,$username,$userPwd);

Login Logs - Send email to admin once

So im in a pickle..
I've created my classes which works fine, as does the sending of the email however, if the user keeps pressing login it'll send the email over and over where it should only send it one time. I have either placed it in the wrong place or I need add something else to it of which I'm a bit lost.
Here's my code:
public function login($username, $password)
{
if (!empty($username) || !empty($password))
{
$ip = $_SERVER['REMOTE_ADDR'];
$stmt = $this->run("SELECT * FROM `users` WHERE `username` = ?");
$stmt->execute([$username]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$blocked = $this->run("SELECT count(*) FROM `failedLogins` WHERE `ipAddress` = ?");
$blocked->execute([$ip]);
$re = $blocked->fetchColumn();
$ipBlock = $this->run("SELECT * FROM `blockedIPS` WHERE `ip` = ?");
$ipBlock->execute([$ip]);
if ($re <= 6) {
if ($ipBlock->rowCount() == 0)
{
if ($stmt->rowCount() > 0) {
if (password_verify($password, $row['password'])) {
$_SESSION['user_session'] = $row['userid'];
$stmt = $this->run("UPDATE `users` SET `loginCount` = `loginCount` + 1, `loginIP` = ? WHERE `username` = ?");
$stmt->execute([$ip, $username]);
$add = $this->run("INSERT INTO `loginLog` (`username`,`ipAddress`, `date`) VALUES (?,?, NOW())");
$add->execute([$username, $ip]);
$this->redirect('home');
} else {
$stmt = $this->run("INSERT INTO `failedLogins`(`username`,`password`,`ipAddress`,`when`,`reason`) VALUES (?,?,?,NOW(),'Incorrect Password')");
$stmt->execute([$username, $password, $ip]);
echo Common::warning('The password you have entered is incorrect');
}
} else {
$stmt = $this->run("INSERT INTO `failedLogins`(`username`,`password`,`ipAddress`,`when`, `reason`) VALUES (?,?,?,NOW(), 'Username guess, possible brute force')");
$stmt->execute([$username, $password, $ip]);
echo Common::error('This username doesn\'t exist.');
}
} else {
Common::emailAdmin("The following IP address has now been blocked from logging in: $ip");
echo Common::error('Your IP address has been blocked from accessing our website.');
}
} else {
$stmt = $this->run("INSERT INTO `blockedIPS`(`ip`,`date`) VALUES (?,NOW())");
$stmt->execute([$ip]);
echo Common::error('You have tried to log in too many times incorrectly. Your account has now been frozen.');
}
} else {
echo Common::warning('Please fill in both fields.');
}
}
Chances are i've misplaced it but a second pair of eyes to glance over and tell me where i've messed up would be great!
I would remove the else part of the code:
else {
Common::emailAdmin("The following IP address has now been blocked from logging in: $ip");
echo Common::error('Your IP address has been blocked from accessing our website.');
}
And move the email line into the else where you update blockedIPS, e.g.:
$stmt = $this->run("INSERT INTO `blockedIPS`(`ip`,`date`) VALUES (?,NOW())");
$stmt->execute([$ip]);
echo Common::error('You have tried to log in too many times incorrectly. Your account has now been frozen.');
Common::emailAdmin("The following IP address has now been blocked from logging in: $ip");
Since this is where you are actually blocking the IP, it makes to send the email at this stage.
Also, you are not actually blocking the blockedIPS from attempting to login again, you should make sure you prevent these IPs from logging in, regardless of failed attempts.
E.g.
if ($ipBlock->rowCount() >= 1) {
// IP has been blocked already
echo Common::error('You have tried to log in too many times incorrectly. Your account has now been frozen.');
// prevent further access
} else {
// do the rest, including blocking IP here
}

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

PHP/MySQL log in system -

I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.

Categories