0

I want to prevent an empty value from going into a MySQL database

I'm using following but for some reason it is letting the empty values get through...

if (trim($var)= '' || !isset($var)){
header("Location:page.php?er=novariablel");
}
else {
...insert into database
}

Note, there is a bunch of complicated stuff that sets the value of var which is why I want to have both the ='' and the !isset because either might be the case.

Am I missing something with the or statement, i.e. it evaluates to false if both are true. Or what am I doing wrong?

6 Answers 6

5

You're lacking an = for your Equal Comparison Operator inside your if statement. Try:

if (trim($var) == '' || !isset($var)){
Sign up to request clarification or add additional context in comments.

2 Comments

No problem, just keep in mind to use == or === equality operators inside your conditional statements in future, otherwise you'll run in the same problem again. :)
Calling trim() before isset() doesn't make sense. If the variable isn't declared, then trim() will complain. If the variable is declared, then isset() is inappropriate.
3

Try:

if (!isset($var) || empty(trim($var))){

empty() is a better way to check to see if a variable has no value. Just keep in mind that the following will return true:

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Comments

0

Try:

$var = trim($var);
if (!empty($var)){
  //not empty
}

1 Comment

trim() before an empty() call doesn't make sense. If the variable isn't declared, then trim() will complain. If the variable is declared, then empty() is doing too much.
0

Try

if (strlen(trim($var)))==0

Comments

0

You should also have put a constraint in your database table attribute that it will not accept NULL values. Then your entry would have not been made in the database.

Comments

0

@John this is great advice.

empty(trim($var))

I've been programming for 6 years and I never thought of trimming the variable before checking to see if it's empty.

1 Comment

This answer is not good advice. If $var isn't declared, then trim() will complain. If $var is declared, then empty() is doing too much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.