March 23, 2012
How to check if form field is empty using PHP
Question by Lap Ming Lee
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();
}
?>
Answer by Baba
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
🙂
Answer by Starx
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.