Ds.109
Ds.109

Reputation: 730

PHP empty not working

I am just trying to check if a form variable is empty. The code sets the variables $getsubject and $getsubject to the $_POST of the form, then I am checking if they are, empty and if they are I want to set them to "No Message" or "No Subject". I tried with isset as well and it didn't work. I even tried setting an else statement that does the same thing and it doesn't change it.

$getsubject = $_POST['subject'];
$getmessage = $_POST['message'];

if(empty($getsubject)) {    
    $getsubject = "<No Subject>";
}

if(empty($getmessage)){ 
    $getmessage = "<No Message>";
}

Upvotes: 0

Views: 1717

Answers (3)

artur99
artur99

Reputation: 818

If you are not sure id the data from the form exist you must use !isset to check it before you declare the variables, so:

if(!isset($getsubject)) {    
    $getsubject = "<No Subject>";
}
else{
$getsubject = $_POST['subject'];
}

if(!isset($getmessage)){ 
    $getmessage = "<No Message>";
}
else{
$getmessage = $_POST['message'];
}

The data from $_POST['subject'];, for example, might not exist, and if you declare it php will give you an error

Upvotes: 0

Derick Renwick
Derick Renwick

Reputation: 21

I suggest that you use a full if conditional to display the results you are looking for combined with html.

IF subject has content then echo Great subject ELSE then echo No Subject END IF

IF message has content then echo Thank You for the message ELSE then echo No Messgae was entered END IF

^this is the basic logic not the code Also look into the trim php code which will trim blank space off of the submission. This helps eliminate blank responses or spaces counting as characters (will not remove space between characters)

Upvotes: -2

Ds.109
Ds.109

Reputation: 730

I found the problem .. the code is working - however the since there were brackets "<" and ">" ... when I retrieved the data from the SQL table, it was not appearing. Not sure why, but when I removed the brackets it worked.

Upvotes: 4

Related Questions