I don't know what's wrong with this code SQL - php

I'm new to PHP and Mysql, for some reason it only checks for statement if($email == $result2 ) wether the input is username or email. I don't know why? can someone explain it logically, i'm stuck for hours figuring it out. :( Thanks Please be kind.
<?php
session_start();
include_once("connect.php");
$email = $_POST['email'];
$username = $_POST['username'];
//echo $_POST['email'];
if(isset($_POST['email']) )
{
$extract= mysql_query("SELECT username, email FROM users");
$resultq = mysql_num_rows($extract);
while($row= mysql_fetch_array($extract))
{
$result = $row['username'];
$result2 = $row['email'];
//$pass = $_POST['pass'];
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
exit(); //break;
}
if ($username == $result )
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
exit(); //break;
}
else
{
}
}
}

It's behaving as written. If either if() test succeeds, you tell the script to exit().
Remove the exit() calls...
You also really REALLY need to learn about WHERE clauses in queries. You are sucking across your entire user table and comparing the records one at a time. This is the equivalent of driving to the grocery store, buying up the ENTIRE store's inventory, driving it home... then throwing it all in the garbage because all you really wanted was one candy bar.

I think you better use unique in your email and username column, then you don't need to check it anymore, mysql will do that for you!

Does it go into the second if statement ( if ($username == $result ) ) after you comment out the first one ( if ($username == $result )) ?
If so, then it keeps hitting that exit() function.

Guys i kinda guessed the answer from combining some of your comments. for some reason i need to include isset($_POST['username']) along with isset($_POST['email']) in order for my if Statements to be all executed... perhaps it was the isset checking if there is a value for username.

try this
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
//---------removed that line
}
else if ($username == $result ) //add else if instead of if
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
//----------removed that line
}
else
{
}
EDIT:
change this
if(isset($_POST['email']) )
to
if(isset($_POST['email']) or isset($_POST['username']))
this to check them both. you are checking just email thats why you dont get the second if.

change this line the following line:
$extract= mysql_query("SELECT username, email FROM users");
Then use where clause as follows:
$extract= mysql_query("SELECT username, email FROM users where username='$username' and email='$email'");

Related

how to disable user account php/mysql

I am trying to have user accounts that can be enabled or disabled.
I have a active field in my table that is set to either yes or no.
This is my code for the login page.
<?php
/* User login process, checks if user exists and password is correct */
require_once 'includes/db.php';
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ($active == '1')
{
if ( password_verify($_POST['password'], $user['password']) ) {
$userid = $_SESSION['userid'];
$_SESSION['email'] = $user['email'];
$_SESSION['firstname'] = $user['firstname'];
$_SESSION['lastname'] = $user['lastname'];
$_SESSION['username'] = $user['username'];
$_SESSION['paynum'] = $user['paynum'];
$_SESSION['empnum'] = $user['empnum'];
$_SESSION['phone'] = $user['phone'];
$_SESSION['active'] = $user['active'];
$_SESSION['lastlogin'] = $user['lastlogin'];
$_SESSION['signup'] = $user['signup'];
$_SESSION['lastupdate'] = $user['lastupdate'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
$update = $mysqli->query("UPDATE dxd_membership SET lastlogin=NOW() WHERE email = '$email'");
header("location: welcome.php");
}
else {
$_SESSION['message'] = "You have entered wrong password please try again!";
header("location: error.php");
}
}
else {
header("location: disabled.php");
}
}
?>
I am sure it is a silly error i have here but it will not check the active field and then either let the user login to the welcome.php page if active is yes or send them to the disabled.php page if their account active is set to no (disabled).
Can anyone help me with correcting the code so that it will work.
Thanks
Look, I see several issues in your code. The first is the double query for the same data. You can simplify this whole thing to one query.
Another (and more important) is the fact that you're just appending data to the SQL query, where the whole objective of MySQLi is to avoid injections by binding params. So a -more- correct way to do it would be this one:
EDIT: escape_string avoids this. I completely ignored it.
<?php
/* User login process, checks if user exists and password is correct */
require_once 'includes/db.php';
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '{$email}'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("Location: error.php");
exit; // Add an "exit" here, because if you add something else, it will run too (even if you asked to redirect... basically is the browser the one that chooses if it follows the redirect or not, but your script still goes on).
}
else { // User exists
$user = $result->fetch_assoc();
// There's no point in filtering using another MySQL query, since YOU ALREADY HAVE THIS DATA. Just use PHP to read it and act appropiately.
// Doing another query is just WASTING resources for no useful purpose.
//$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ( $user['active'] == 'YES' ) {
// Your processing here, you get the idea
}
}
?>
Of course, the best alternative is to use a MySQLi statement and use bind_param/execute. This example is only to follow your style of using MySQLi.
It's pretty obvious
$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ($active == '1') //<-- see it
{
if ( password_verify($_POST['password'], $user['password']) )
Try this
if ($active->num_rows == 1 ) //or != 0 This is false or a result set.
Even if you did have the value of their active filed in there ( you have select * ) you would still be checking string '1' against string 'YES'
Please note I haven't used mysqli in about 4 years, as I use PDO. So that might not be the entire problem, but just seemed wrong..
In fact that second query is not needed as you already have the data you seek, so you can change it.
Now if you are sure active will always be YES for them being active, the $user already contains this data, so why not use it like this, and save the query.
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error.php");
}else { // User exists
$user = $result->fetch_assoc();
/* comment these next 2 lines out when not debugging */
echo "<pre>"; //whitespace formating
var_export( $user );
if ($user['active'] == 'YES'){
// .....
}
}
One thing I feel compelled to mention is that you should look into prepared statements. You can find information on that here
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Whenever you concatenate in a SQL query you should be using a prepared statement instead, as it opens you application to SQL injection attacks. Now that I look closer you are using escape_string while this is good, the preferred way is prepared statements. This is because with a prepared statement, the variables are entirely separate from the query commands and so the DB knows not to execute anything in them. Even with escaping there could be edge cases that may be an issue, I don't know of any per-say, but something like using a Hexadecimal version of a quote are things I have seen in examples, or weird character strings that the DB would see as a quote.

Get variable from mySQLi to PHP

I'm pretty new to the whole PHP and mySQLi thing... But at the moment I am trying to make a simple project where I would like to read a specific value from a mySQL database, and then simply print (echo) it..
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '' || $password == ''){
echo 'please fill all values';
}else{
require_once('dbConnect.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo 'All values match!';
}else{
echo 'These values do not match!';
}
mysqli_close($con);
}
}else{
echo 'error';
}
?>
I don't know if it is that obvious... but this is actually code for an app. But I mainly want to know how to get a specific value from mySQL as a PHP variable?
I will be using the username to search for the correct variables
Let's say the table looks like this :
username password money
guy 123 10
then I want to use 'guy' to find the amount of money and print it to the screen.
Sorry if this is asked and/or explained badly...
change the code like this where you are making query
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($result)){
$money= $row['money'];
}
//So because your query will return only one user if the ///username is unique so //now you can print money anywhere.

Php log in allows entry with no user/pass

Hey guys ive put together a basic user log in for a secure admin area and it seems to work great, if you enter a correct user/pass you get access, if you enter the wrong user pass, you get no access. However if you enter nothing in both fields you get access.
This is how it works.
Creating a user, a basic form POSTS to this php file.
<?php
$con = mysqli_connect(credentials are all good) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$some_str = md5(uniqid(mt_rand(), true));
$base_64str = base64_encode($some_str);
$modified_base64 = str_replace('+', '.', $base_64str);
$gensalt = substr($modified_base64, 0, 22);
$format_str = "$2y$10$"; // 2y for Blowfish and 10 times.
$salt = $format_str . $gensalt . "$";
$hashed_pass = crypt($escapedPass, $salt);
$query = "INSERT INTO `userpass` (`username`, `password`, `salt`) VALUES ('$escapedUser', '$hashed_pass', '$salt'); ";
if(isset($escapedUser) && isset($hashed_pass))
{
mysqli_query($con, $query);
header("Location: ausers.php");
exit();
}
Echo "Something went wrong!";
?>
The database appears to be storing these fine
We then log in with this code
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$saltQuery = "select salt from userpass where username = '$escapedUser';";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
if(isset($escapedUser) && isset($hashed_pass))
{
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
}
header("Location: alogin.htm");
exit();
}
Echo "Something went wrong!";
?>
So as i said, this seems to work fine for when any user pass combination is given whether access granted or denied however using no user and pass and pressing log in allows entry. Any ideas? THeres no blank rows in the database table.
Side question, is this salt/hash method correct, its my first attempt.
For your login code, your condition relies on an isset() test. You perform this test on $escapedUser and $hashed_pass. Both of these variables were actually assigned values earlier in the code! Once you assign a value to the variable, it will pass the isset() test, even if the value is an empty string. You might want to use an empty() check, perhaps on the original $_POST variables.
Moving on to the inner condition, which tests if the mysql query returns exactly 1 row of results. If there were truly no rows with empty values, then this condition would never pass because the query would return 0 rows. But it is passing. Two things to consider:
Notice that your registering code uses the same isset() test. Therefore it is very possible that someone used your registration form, submitted empty fields, and successfully registered a row with empty user and password fields. Have you explicitly queried your database for empty fields and actually come up with 0 results?
Your query uses SELECT *. Perhaps this is causing the query to return some sort of aggregate value (like a COUNT() or something that always has a result no matter what). Perhaps try explicitly defining the columns to return?
I cannot comment on your salt/hash method as I have no experience in that part. Hope you find this helpful!
In my opinion you need more than one level of checks in any form, whether it be registration, comments, login, etc. The way I prefer to go about it is a tiered approach. It may work better for you, but it's just an example.
By doing it this way, you ensure that your input will never be empty. Another issue I see with your login script is that you never compare the input with the database so how can you know if they entered the correct information? The only thing allowing them to login is that the query returned a record. This is also why they can login with a blank form.
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
/* Ensures that form was submitted before any processing is done */
if (isset($_POST)) {
$User = $_POST['user']);
$Pass = $_POST['pass']);
if (!empty($User)) {
if (!empty($Pass)) {
$escapedUser = mysqli_real_escape_string($con, $User);
$escapedPass = mysqli_real_escape_string($con, $Pass);
/* you need to verify the password here, before adding the salt */
$saltQuery = "select salt from userpass where username = '$escapedUser'";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
/* you need to verify the username somewhere here */
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
} else {
header("Location: alogin.htm");
exit();
}
} else {
echo "Please enter a password.";
}
} else {
echo "Please enter a username.";
}
} else {
echo "You have not entered any information.";
}
?>

Check if activation_code is not activeted at login. "ONLY" activation_code

This is the code I use at login:
$q = $lacz->query("SELECT email, pass, activation_code
FROM users
WHERE email='". $nazwa_uz_l ."'
AND pass = '". $haslo_l ."'
AND activation_code IS NULL ");
if($q->num_rows>0) {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l; }
else
{
echo 'Pass or Log are wrong, or activation code is not confirmed (check email).';
exit;
}
In this query I check for all 3 things: email, password and activation code, and then output an error. What I want to do is to output an first error when Pass or Log are wrong and second error (something like elseif) when activation code IS not NULL. I tried else if and two queries, but I was getting the errors. Can You help me? I check the answers and give points, thanks.
Remove "AND activation_code IS NULL" from your query and do something like
if($q->num_rows>0)
{
$row = $q->fetch_assoc();
if(!is_null($row['activation_code']))
{
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
}
else
{
echo 'Activation code is not confirmed (check email).';
exit;
}
}
else
{
echo 'Pass or Log are wrong.';
exit;
}
Don't check the activation code in the query. Just get the user information, along with the activation code field:
SELECT email, pass, activation_code
..
WHERE email='foo' and pass='bar'
Then you can test the individual conditions in your code:
if (number_of_rows == 0) {
... bad username/password
} else if ($activation_code == '') {
... code is blank/null
}
If you remove the AND activation_code IS NULL from the query's WHERE clause, you'll be able to pull data for a user matching the given email/password. Then, with that, you'll be able to determine if the user exists, or if their activation code is empty:
$q = $lacz->query("SELECT email, pass, activation_code
FROM users
WHERE email='". $nazwa_uz_l ."'
AND pass = '". $haslo_l ."'");
if ($q->num_rows === 0) {
echo 'Password or email address are wrong.';
exit;
} else {
$row = $result->fetch_assoc();
if (empty($row['activation_code'])) {
echo 'Activation code is not confirmed.';
exit;
} else {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
}
}
Side-note (not answer related): I highly suggest using a parameterized query instead of directly inserting the values into the SQL; if you prefer the current way, make sure you're sanitizing the input first to prevent SQL Injection.

Unable to check for password and username at login

I have tried to create a PHP log in form. My code is as follows. The if-else statement is not functioning well. Please solve this.
$connect = mysql_connect("localhost", "root", ""); //connect
mysql_select_db("elective_mgmt", $connect);
$username = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * from verify_student where
username='$username' && password='$password'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (name == $username && password == $password)
echo "you are logged in";
else
echo "please recheck your password and username";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "you are logged in";
}
else
echo "please recheck your password and username";
You can also do this by counting the number of rows. In your code $row is an array so whenver you need to acces the array elements do this $row['name']
You have a problem here.
if(name==$username && password==$password)
It should be
if($row['name']==$username && $row['password']==$password)
OR
if(mysql_num_rows($result) == 1)
You should look at - Why shouldn't I use mysql_* functions in PHP?
You could remove your if/else statement since you check the inputs already with your mysql query (name && password) and replace it with a mysql_num_rows == 1 (as the others have already mentioned before).
It seems that you are new to php and creating log in forms, so let me give you a good advice:
input values for a log in form shouldn't be passed via URL, use method post instead
never save passwords unencrypted (use sha512 since md5 is considered unsafe)
never use single information to store the log in status in the session

Categories