Login system No errors and no data inserted to the database


#1

I have no errors and nothing is inserted in my database.

here is my code for signup.php

ANY HELP WILL BE APPRECIATED

 ini_set('display_errors', '1');
 ini_set('display_startup_errors', '1');
 error_reporting(E_ALL);


include_once 'conn.php'; 

if(isset($_POST['signup'])){

	
 	$email = $_POST['email'];
 	$username = $_POST['username'];
 	$password = $_POST['password'];

 	
    $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
    $stmt = $dbh->prepare($sql);
    
   
    $stmt->bindValue(':username', $username);
    

    $stmt->execute();
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
   
    if($row['num'] > 0){
        die('That username already exists!');
    }


 	
 	$hash = password_hash($password, PASSWORD_DEFAULT);



	$sql = "INSERT INTO users (username, email, password, join_date)
 				  VALUES (:username, :email, :password, now())";

 	
 	$stmt = $dbh->prepare($sql);

 	
 	$stmt->bindValue(':email', $email);
    $stmt->bindValue(':username', $username);
    $stmt->bindValue(':password', $hash);
    


 	
 	$result = $stmt->execute(array(':username' => $username, ':email' => $email, ':password' => $hash  ));


 	if ($result){ 

 		header('Location: login.php');
        exit;

    } 
}

 ?>```

#2

Your logic is incorrect. You dont check for a username. You are creating a race condition. What you do is set a unique constraint on the column, attempt the insert and capture the duplicate error if any.

Also, depending on the name of a button to be submitted in order for your script to work will completely fail in certain cases. You need to check the REQUEST METHOD. Do not create variables for nothing.


#3

Adding onto what @benanamen had said, there’s a lot of redundant code you have there. You use bindValue, but then you start executing an array. Kind of makes no sense. Not only that, there is really no need to use COUNT since it wouldn’t make sense to total up 1 username if it exists.


How to check if a username is already taken
#4

Thank you I will do that…


#5

thanks much appreciated…


#6

8 posts were split to a new topic: How to check if a username is already taken


#7

Do you have any idea to do that…Coz i’ve tried to change from signup to email and it worked

if(isset($_POST['email'])){

also tried using same the username and it gave me and error message that the username exists… Meaning COUNT worked perfectly okay. @spaceshiptrooper


#8

My three thoughts, just in general:

  • Check for $_SERVER['REQUEST_METHOD'] instead of looking for something in the $_POST array
  • Check for errors after you run each query, you’re just assuming everything worked
  • If you want to just insert the current date/time into the table, just set that as the default for the column and leave it out of the query.

The point about using a unique constraint is that, the way you do it, there is a short time between running your first query to check for a username, and running the second query to insert the new user, where another user could do the same check for the same username. This would result in both usernames being inserted into the database. If you configure the table so that the column username has the “unique” flag on it, you will get an error when the second user is created, even if the first query passed. But you must check for that error after the insert, and if you’re going to do that, then the first query is no longer required.


#16

Hey guys I am kinda new to PHP here!!! and I am mixed up, i don know which is which now and also the right way to follow need some guidance and stuff. Thanks!


#17

Well, the first thing is to clean this up. Either pick bindValue or execute it through the execute() function. Doing both of them makes absolutely no sense other then clogging up unneeded processes for this redundancy.


#18

thanks @spaceshiptrooper


#19

here is the code

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

include_once 'connect/conn.php'; 


if(isset($_POST['email'])){

    //collect form data and store in variables

    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];

    //hashing the pasword
    $hash = password_hash($password, PASSWORD_DEFAULT);

    //create SQL insert statement

    $sql = "INSERT INTO users (username, email, password, join_date)
                  VALUES (:username, :email, :password, now())";

    //use PDO prepared statement to sanitize the data

    $stmt = $dbh->prepare($sql);

    //add the data into the databse using the exec function

    $stmt->execute(array(':username' => $username, ':email' => $email, ':password' => $hash  ));

    // checking if one row was created

    if ($stmt->rowCount() == 1){ 

        //echo "<p style='color:green;'>Registration Successful</p>";

    } else { 

        //echo "<p style='color:green;'>Kindly register</p>";

    } 
}

 ?>```

#20

It actually looks pretty decent now. Next, I would remove the if(isset($_POST['email'])) part and replace it with if($_SERVER[REQUEST_METHOD'] == 'POST'). The only time when if(isset($_POST['email'])) should be acceptable is during form validation. Form validation is the process in which one does to validate and make sure that those fields does indeed contain what you want it to contain. For instance, a surname shouldn’t have numbers. That’s the only time when using if(isset($_POST['email'])) is appropriate. The reason why is because people can modify and remove elements from your screen. Without you validating that these fields do exist, you are going to get a lot of Undefined Index errors. To avoid this, it is inevitable not to use if(isset($_POST['email'])) so this should only be the time when it’s appropriate to use. Other than that, if you are just checking for form submission, then use the proper one which is if($_SERVER[REQUEST_METHOD'] == 'POST').

There is 1 last thing, but I will let you fix this piece before we continue.


#21

I am having a hard time keeping up with where you actually are between this forum and this one https://forums.phpfreaks.com/topic/307734-login-form-not-working/?tab=comments#comment-1561183


#22

@benanamen
Yes I know I was waiting a reply on this forum on my registration part still on the login system. So i decided to move on to the login part that is why i pasted it on the other forum so that not to bring confusion on this thread
i guess you’re on the other forum that’s why you got it confused.

but let us continue on this thread since i have some things to fix.


#23

Finished that already…

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

include_once 'connect/conn.php'; 

if($_SERVER['REQUEST_METHOD']) === 'POST') {

	//collect form data and store in variables

 	$email = $_POST['email'];
	$username = $_POST['username'];
 	$password = $_POST['password'];
 	

 	//hashing the password
 	$hash = password_hash($password, PASSWORD_DEFAULT);

 	//create SQL insert statement

	$sql = "INSERT INTO users (username, email, password, join_date)
 				  VALUES (:username, :email, :password, now())";

 	//use PDO prepared statement to sanitize the data

 	$stmt = $dbh->prepare($sql);


 	//add the data into the databse using the exec function

 	$result = $stmt->execute(array(':username' => $username, ':email' => $email, ':password' => $hash  ));

 	// checking if one row was created

 	if ($stmt->rowCount() == 1){ 

 		header('Location: http://localhost/auth/login.php');
        exit;

    } 

}```

#24

Ok. Now I can address the last piece that I find might be causing the problem. So I think the whole entire actual reason why it isn’t inserting data is because the database connection is not within the scope for the query to run. I have seen this happen once with another member on here. The way we got it to work was I told him to place the included database connection inside the if statement. I’m not sure if it’s going to work with yours, but you can try it.


#25

It has inserted data without including it in the ‘if’ statement, I think I forgot to refresh the page earlier on after editing the code. Its working perfectly now.


#26

You might want to fix this bit though. It’s not correct.


#27

I guess this is correct

if($_SERVER['REQUEST_METHOD'] == 'POST') {