سؤال

I have a bunch of text box's on my page that involve numbers. The default value in the database is NULL when it is created and I have each input echo the value it is in the database (by default nothing since it is set to null).

The problem I am having is, if the user opens the form for the first time, submits the form and doesn't fill out an item, the value get's turned to 0 instead of keeping it null.

Could anyone help me?


When a user opens the page, it formats the numbers like so:

if(isset($data['variable1']))
    $variable1 = numberFormat($data['variable1']);
else
    $variable1 = "";

When a user posts the form, it unformats the numbers like so:

$variable1 = numberUnformat($_POST['variable1']);

I have even tried doing this:

if(isset($_POST['variable1']))
    $variable1 = numberUnformat($_POST['variable1']);
else
    $variable1 = "";

numberFormat()

function numberFormat($n, $n_decimals="2")
{
    return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals));
}

numberUnformat()

function numberUnformat($number)
{
      $cleanString = preg_replace('/[^0-9.,-]|(?<=.)-/', '', $number);
      $onlyNumbersString = preg_replace('/[^0-9-]|(?<=.)-/', '', $number);

      $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
      $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString,           $separatorsCountToBeErased);
      $removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);

      return (float) str_replace(',', '.', $removedThousendSeparator);
}
هل كانت مفيدة؟

المحلول

if(isset($_POST['variable1']))

$_POST['variable1'] will always be set if it was part of the form. HTTP POST values (or anything else transmitted over HTTP for that matter) are never null, because that's not a type in HTTP. The best it is is an empty string, which is not null, so the above condition is always true and your unformat function will always return 0.

You'll have to check for strlen($_POST['variable1']) > 0 or $_POST['variable1'] !== '' instead.

نصائح أخرى

Because it is included in your form post, that variable is technically set (set to ''), this is what you will need to check for.

A simple method could be

if(strlen(trim($data['variable1'])) > 0)
{
  $variable1 = numberFormat($data['variable1']);
}
else
{
  $variable = null;
}

Depending on what you actually want to do. So here we are removing all whitespace before and after and then testing the length of the input, if it is more than 0, then the user entered something, otherwise we turn it into a true null.

isset($_GET['data']) is always true if you have input name="data" even if it is empty

you should check $_GET['data'] === '' too (or $_POST)

Try This

 if(isset($data['variable1']) && !is_null($data['variable1']))
    $variable1 = numberFormat($data['variable1']);
 else
    $variable1 = "";
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top