user1187135
user1187135

Reputation:

How to check if form field is empty using PHP

I am trying to check if the field is empty. If it is, redirect to sign uppage. Right now, it just keeps on creating multiple account with NULL username and password. I tried using strlen(), but it doesn't seem to be working.

<?php
        try{
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $hash = crypt($password_signup, '$3a$08$2'); // salt 

        $connection = new PDO ('mysql:host=localhost;dbname=tongue', 'web', 'lapming1');
        $connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $connection -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        require_once("functions.php");

        $sql = 'SELECT email, hash FROM user WHERE email=:username';
        $row = login ($sql, $connection, $username_signup);

        if ($username = false){
            header("Location: sign_up.php?error");
        };

        if ($row) {
            header("Location: sign_up.php?msg=1");
        }
        else {
            $sql = 'INSERT INTO user(email, hash) VALUES (:username, :password)';
            create($sql, $connection, $username_signup, $password_signup);
            header("Location: index.php");
        };


    $connection = null;

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>

Upvotes: 1

Views: 7547

Answers (3)

Baba
Baba

Reputation: 95161

I can see the error .. you are using basic assignment operator "=" insted of Comparison operators "=="

Change

   if ($username = false){
        header("Location: sign_up.php?error");
    };

To

   if ($username == false){
        header("Location: sign_up.php?error");
    };

Or Better Approach

  if (empty($username){
        header("Location: sign_up.php?error");
    };

Thanks :)

Upvotes: 2

Starx
Starx

Reputation: 79069

Its easier this way

if (!strlen($username)){
 header("Location: sign_up.php?error");
};

And you are not using correct comparison operators

$username = false assigns the boolean value false to $username and will always be returned as true, and thus the header will keep on being sent.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205


$username = trim($_POST['username']);
if(!empty($username)) {
   ....is not empty
}

Upvotes: 2

Related Questions