Jump to content

IF statement driving me nuts


tet3828

Recommended Posts

I am simply trying to verify that two fields in my form are not empty.

 

 

But apparently I am not doing something right. Check it:

 

if (isset($_POST['field1']) == FALSE  AND if isset($_POST['field2']) == FALSE  ) {

//Tell the user both fields are empty, you suck try again.

}

Link to comment
Share on other sites

You've used 'if' twice, you don't need it after the 'AND'. Also, as the above comment suggests, the variables may be set but still empty in which case you need to use the empty() function. Or just check if they are false with:

if(!$_POST['field1'] && !$_POST['field2'])

Link to comment
Share on other sites

The problem with using both the "empty()" test and the test for "false" is that these will give false positives when the field value is "0" (zero). The only way to really make sure the field is empty is to use the strlen() function. See the following example:

<?php
if (isset($_POST['submit'])) {
echo '<pre>'. print_r($_POST,true) . '</pre>';
if(empty($_POST['field1']) && empty($_POST['field2']))
	echo 'Both fields are empty<br>';
if(!$_POST['field1'] && !$_POST['field2'])
	echo 'Both fields are false<br>';
if(strlen(trim($_POST['field1'])) == 0 && strlen(trim($_POST['field2'])) == 0)
	echo 'Both fields are really empty<br>';	
}?>
<html>
<head>
<title>Test empty</title>
</head>
<body>
<form method="post">
	Field 1: <input type="text" name="field1"><br>
	Field 2: <input type="text" name="field2"><br>
	<input type="submit" name="submit">
</form>
</body>
</html>

 

Try running this code putting the zero character into each field and see the results.

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.