How to handle optional form fields

I have several fields that may be empty when the form is submitted.
If I fill every field with valid entries, the row is created in the table.
If I leave an optional field empty, the database does not get a new row.

		if ($fn && $mi && $ln && $e1 && $e2 && $s1 && $s2 && $c && $z && $fax && $pho && $phh && $phc && $cell && $w1 && $w2 && $st) { // If everything's OK.

		echo "<p> $fn $mi $ln $e1 $e2 $s1 $s2 $c $st $z $fax $pho $phh $phc $cell $w1 $w2</p>";
$query = "INSERT INTO ....................";

I am not getting any errors, but the echo of variables before the if statement does display.


$fn = '';

if( $fn ) {
   echo 'Yes';
}
else {
  echo 'No';
}

An empty string evaluates to false. So your long test “if everything is OK” will be false if any of those values are empty strings. When that’s the case, no query runs.

You need to validate the value when it’s not empty. Empty optional fields can go in the database.

You should consider setting default values in your database table, even if that is a null.

As for not wanting to wastefully check for items not submitted, be aware there are two ways of inserting data.

If you take this example table (sorry, I had to guess at the exact settings)


tbl_name
=======
id | INT auto-increment
a | INT
b | INT
c | INT
x | INT default 0
y | VARCHAR (20) default ''
z | TIMESTAMP  - default current_timestamp

a) insert a full row every time


INSERT INTO tbl_name VALUES(0,1,2,3, 23, 'a string', '2011-12-16 12:00:00');

b) insert just the named fields - as long as the db has defaults set for each field which CAN be sometimes not set.


INSERT INTO tbl_name (a,b,c) VALUES(1,2,3);

So, if your incoming data is something like:

$_POST[‘a’] = ‘11’;
$_POST[‘b’] = ‘22’;
$_POST[‘c’] = ‘33’;
$_POST[‘x’] = ‘44’;

If you are careful you can validate this data against expectations and create something which spits out:


INSERT INTO tbl_name (a,b,c,x) VALUES(11,22,33,44);

PDO and its prepared statements is a good tool to help you achieve this (ditto Mysqli no doubt).

OKAY! I am learning something (as usual). :slight_smile:

This is the code i have to validate one of my optional fields (as modified to add a null?):

	// Check for a middle initial.
		if (preg_match ('%^[A-Za-z\\.\\' \\-]{1,15}$%', stripslashes(trim($_POST['mid_int'])))) {
		$mi = escape_data($_POST['mid_int']);
		} else if (empty($_POST['mid_int'])) {
		$mi = NULL;
    // allowed to be empty, optional, not required
	    } else {
		$mi = FALSE;
		echo '<p style="color:red;">Please enter a valid middle initial.</b>!</p>';
		} // end of check for mid_int

I will be giving this code a test.

That did not work, but a little more research allowed me to find the solution.

$mi = "NULL"; // quotes make it work and once again I have been pointed to another learning experience.

My wife thinks I need to build a notebook with everything I am learning on this project. (I have already started the notebook.) :slight_smile:

Two ways to achieve the same request:

  1. From Database: setting default values in your database table, even if that is a null i.e put the default value ‘’ for all varchar fields.
  2. From Script: Need to validate the single check instead of all in one go.
    Example:

Function chkValue($val){
if( $fn ) return $fn;
return ‘blank’;
}

$FN=chkValue($fn);

So in this way you can get the value of all fields whether they are empty or not.

But that will put strings into your database containing the text ‘NULL’, as opposed to actually saving a NULL.
Or is that what you’re after? Or have I missed something because I only scanned the rest of the topic :wink:

I noticed that. While I would have preferred that the entry was actually empty (null), I have adjusted by looking for NULL when I am using the information and changing the variable to “”.

I will check the function that SnapseIndia posted in message #5.