PHP problem - unknown problem.

+2 Jad Samadi · December 23, 2014
So hey there guys i want to start first by thinking you for helping me in the previous problems i had and well yet i have a new one today .
As i was working on my login/Register system i actually was surprised to realize something new in PHP .... or maybe its just my fault .
Any way let me show you what is happening .
This is my code : 


<?php


include 'core/init.php';





if (empty($_POST) === false) {


$username = $_POST['username'];


$password = $_POST['password'];





          if (empty($username) === true || empty($password) === true) {


             $errors[] = 'You need to enter a username and a password';


          } else if(user_exists($username) === false) {


            $errors[] = 'We can\'t find that username. Have you registered ?';


          }else if (user_active() === false) {


            $errors[] = 'You haven\'t activated your account';


          } else { 


           //here


          }











print_r($errors);


}


?>



i don't suppose any thing is wrong in there yet when you test it you will notice that one of the 'else if' statements don't actually work . ... its like the file is only reading the first one.
Ill explain more . I opened my index page and tried to login with empty username and password boxes . It gives me this error :
Array ( [0] => You need to enter a username and a password )
witch is great ... that means it works !
Now i tried to test if the 'user_exists' function work . So i entered a username and password that isn't saved in my database and i got that error :
Array ( [0] => We can't find that username. Have you registered ? )
Works great ! Now the problem .... When i try to test the 'user_active' function it doesn't work ... I enter the username and password that is saved in my database with the active state equal to 0 where i should then get the error :
You haven\'t activated your account
But instead i get this error :
Array ( [0] => We can't find that username. Have you registered ? )
Now i know i probably made a mistake in the function so it does not work but no i didn't.
I tried to switch the active function and the exists one and my code became :


<?php


include 'core/init.php';





if (empty($_POST) === false) {


$username = $_POST['username'];


$password = $_POST['password'];





          if (empty($username) === true || empty($password) === true) {


             $errors[] = 'You need to enter a username and a password';


          }else if (user_active() === false) {


            $errors[] = 'You haven\'t activated your account';


          } else if(user_exists($username) === false) {


            $errors[] = 'We can\'t find that username. Have you registered ?';


          } else { 


           //here


          }











print_r($errors);


}


?>



And for some reason now i cant get this error :
Array ( [0] => We can't find that username. Have you registered ? )
instead i get this one :
Array ( [0] => You haven't activated your account )
So ye ... for both cases if i enter a correct or incorrect username/password.
I don't think i can explain more and i think this code would help as well(the functions) :


<?php





function user_exists($username){


         $username = sanitize($username);


         return (mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `username` = '$username'"), 0) ==1) ? true : false;


}





function user_active($username){


         $username = sanitize($username);


         return (mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1"), 0) ==1) ? true : false;


}





?>




So if you can help me i would really appreciate it .Thanks for reading

Post a Reply

Replies

- page 2
Oldest  Newest  Rating
0 Jad Samadi · December 24, 2014
nope still not working :/ i don't know what is happening ...
0 Ron Butcher · December 27, 2014
No problem, I didn't put any error checking into the database queries, so lets do that.  We also need to make sure that your database has the table layout we are looking for and that we are connecting properly.

This is how my database is setup, I have a database called 'test' with a table called 'users' that has the following information:

+---------+----------+----------+--------+
| user_id | username | password | active |
+---------+----------+----------+--------+
|       1 | ron      | ron      |      1 |
|       2 | dave     | dave     |      0 |
+---------+----------+----------+--------+

At the start of my page I include the database connect info and connect to the database like this:

<?php
// Define database connection variables
$host="localhost";
$dbUser="database_user";
$dbPass="database_password";
$dbName="database_nema";

// Connect to the database
$mysqli = new mysqli("$host", "$dbUser", "$dbPass", "$dbName");

// If there is a problem, kill the page and display the error
if($mysqli->connect_errno)
{
die(mysqli_connect_error());
}

I am pretty sure you defined the function sanitize, but that was not included in any of your code.  Here is how I wrote it:

//  Define the function sanitize
function sanitize($str)
{
global $mysqli; // Since we are calling a variable outside the function, we have to note it is a 'global' variable before using it
return $mysqli->real_escape_string($str);
}


Now I will go into the code, this is mostly what I put above, but with some error checking no my database query and a couple of clean up items as well.
	//  Initialize the error variable
$errors = '';

// See if the form has been submitted
if(!empty($_POST))
{
// Clean the information passed by the form
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

// Check to see if the username or password is empty (!) means false, so the statement basically says, if not empty......
if(!empty($username) || !empty($password))
{
$qry = "SELECT `user_id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'"; // Pull necessary information from the database about the user
$result = $mysqli->query($qry) or die($mysqli->error); // I prefer the OOP method of mysqli, it is just a personal preference.

if($result->num_rows != 1) // Check to make sure that only one result is present
{
$errors = 'Username or Password is Incorrect'; // I don't tell the user which part they entered incorrectly to discourage hackers.
}
else
{
$userData = $result->fetch_object(); // Gather all the users information to finish comparing
// Right here is where I would normally hash and add salt to the $password variable to prepare it to compare to my database.
if($password != $userData->password) // Check to see if the password is correct
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active) // Check to see if the user is active or not
{
$errors = 'This Account is No Longer Active. Please Contact the Site Administrator';
}
else
{
echo 'Login Successful';
// Code to log in user goes here.
// $login_user($userData);
}
}
}
else // This statement only runs if one of the fields was left blank.
{
$errors = 'Please Enter Both A User Name and Password';
}
}

Give that a try.  Hopefully I left enough comments you can understand the process, if not let me know and I can explain further.  I did run this code through my setup before posting this time so you shouldn't get any errors as long as your database is setup properly.
0 Jad Samadi · December 24, 2014
I edited the post and added the codes into code format thing .
0 Jad Samadi · December 28, 2014
Hey thanks for the code now i did not get any errors witch is  super cool BUT
this whole code now : 

<?php



//  Define database connection variables
        $host="localhost";
$dbUser="root";
$dbPass="";
$dbName="lr";

//  Connect to the database
$mysqli = new mysqli("$host", "$dbUser", "$dbPass", "$dbName");

//  If there is a problem, kill the page and display the error
if($mysqli->connect_errno)
{
die(mysqli_connect_error());
}

//  Define the function sanitize
function sanitize($str)
{
global $mysqli;  //  Since we are calling a variable outside the function, we have to note it is a 'global' variable before using it
return $mysqli->real_escape_string($str);
}
//  Initialize the error variable
        $errors = '';

        //  See if the form has been submitted
if(!empty($_POST))
{
//  Clean the information passed by the form
                $username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

                //  Check to see if the username or password is empty (!) means false, so the statement basically says, if not empty......
if(!empty($username) || !empty($password))
{
$qry = "SELECT `user_id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'"; // Pull necessary information from the database about the user
$result = $mysqli->query($qry) or die($mysqli->error);  // I prefer the OOP method of mysqli, it is just a personal preference.

if($result->num_rows != 1) // Check to make sure that only one result is present
{
$errors = 'Username or Password is Incorrect'; // I don't tell the user which part they entered incorrectly to discourage hackers.
}
else
{
$userData = $result->fetch_object(); // Gather all the users information to finish comparing
// Right here is where I would normally hash and add salt to the $password variable to prepare it to compare to my database.
if($password != $userData->password) // Check to see if the password is correct
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active) // Check to see if the user is active or not
{
$errors = 'This Account is No Longer Active. Please Contact the Site Administrator';
}
else
{
echo 'Login Successful';
                                        //  Code to log in user goes here.
                                        //  $login_user($userData);
}
}
}
else // This statement only runs if one of the fields was left blank.
{
$errors = 'Please Enter Both A User Name and Password';
}
}



          

?>


Doesn't work at all and  as you i did edit the database connection info and tried to edit few stuff after posting this code here and yet nothing works ....
Sorry if im being annoying as i said before but i seriously can't understand this new Mysqli and OOP and mysqli thing ...
0 Jay Deshaun · December 28, 2014
MySQLi php functions and examples - http://www.w3schools.com/php/php_ref_mysqli.asp

Does the 'active' return a number or true/false?
0 Jad Samadi · December 28, 2014
i think it should return a true/false 
0 Ron Butcher · December 25, 2014
Did you try the 'or die' statement to see if a mysql error is being produced by your query?
0 Jad Samadi · December 28, 2014
You know what ? your right .... i removed the active bullshit and i t worked finely .... Now its less complicated .
The active had a purpose to show registered users, i don't need that .
Thanks for your help hope you have a merry Christmas and a happy new year . You can close this thread. 
0 Jad Samadi · December 25, 2014
yes i did and the page did die but i don't think the problem is related to the query ....
  • 1
  • 2

PHP

106,963 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators