Jump to content
Larry Ullman's Book Forums

Updating Table - Optional Fields


Recommended Posts

Hi everyone,

 

Happy New Year!

 

Could someone please help me with the following?

 

I'm using a form to update a database table but I'm not sure what to do with values that are optional/not required. Do I set the value to NULL? Also, should I validate any text inputs with FILTER_SANITIZE_STRING?

 

 

Thank you in advance!

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	$errors = array();
	
	// Trim all the incoming data:
	$trimmed = array_map('trim', $_POST);

	// Assume invalid values:
	$name = $order_quantity = FALSE;
	
	// Check for a name:
	if (empty($_POST['name'])) {
		$errors['name'] = 'You forgot to enter your name.';
	} else {
		$name = mysqli_real_escape_string($dbc, $trimmed['name']);
	}
	
	// Check for the order quantity:
	if (filter_var($trimmed['order_quantity'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
		$oq = mysqli_real_escape_string ($dbc, $trimmed['order_quantity']);
	} else {
		$oq = NULL;
	}




	if ($name && $oq ) { // If everything's OK...

			// Make the query:
			$q =”UPDATE....
Link to comment
Share on other sites

For optional values, if the user enters something, I would validate it. If it's valid, insert it into the DB. If it's not valid, I would spit back an error message to the user. And if they didn't input anything, I would enter NULL, an empty string, or 0, depending on what you feel is most appropriate.

 

I personally see NULL as meaning corresponding data does not exist, which feels a bit odd for optional data.

 

I would use NULL if, for example, you have a users table with various types of users, and some types of users have certain types of data that other users don't require. In that case, I would use NULL for the non-applicable data.

 

Just my two cents.

Link to comment
Share on other sites

Thank you for getting back to me HartleySan.

 

Just one question. Before I make the query to update the database, there is a condition to check if the variables are true:

if ($name && $oq )

 

 

But if I set $oq to NULL then that variable is false, which means I can only assign an empty string or 0 to $oq in order for the condition to be true. Is that correct?

 

 

Thank you!

Link to comment
Share on other sites

  • 2 weeks later...
  • 4 weeks later...
 Share

×
×
  • Create New...