条件表单字段检查

条件表单字段检查

问题描述:

I have the following to check weather a form field is populated or not. If the $priceperperson field is set then calculate the $rentalprice based on that, if its not, then calculate the $rental price based on the $baserentalprice.

$priceperperson = ($_POST['priceperperson']);
$baserentalprice = ($_POST['rentalprice']);
$numberofguests = ($_POST['numberofguests']);
 if (isset($priceperperson)) {
  $rentalprice = ($priceperperson * $numberofguests * $numberofnights);
 } elseif (!isset($priceperperson)) {
  $rentalprice = $baserentalprice;
 }

UPDATE: My problem is that I dont seem to be able to set the rental price as $baserentalprice. The $priceperperson calculation works but when i delete the content of the $priceperperson field from the form and fire the ajax again, it wont work. Either way, its failing after the 'else'.

我有以下内容来检查天气是否填充了表格字段。 如果设置了$ priceperperson字段,则根据该字段计算$ rentalprice,如果不是,则根据$ baserentalprice计算$租赁价格。 p>

  $ priceperperson =(  $ _POST ['priceperperson']); 
 $ baserentalprice =($ _POST ['rentalprice']); 
 $ numberofguests =($ _POST ['numberofguests']); 
 if(isset($ priceperperson)){  
 $ rentalprice =($ priceperperson * $ numberofguests * $ numberofnights); 
} elseif(!isset($ priceperperson)){
 $ rentalprice = $ baserentalprice; 
} 
  code>  pre>  
 
 

更新: 我的问题是,我似乎无法将租赁价格设置为$ baserentalprice。 $ priceperperson计算有效但当我从表单中删除$ priceperperson字段的内容并再次激活ajax时,它将无法正常工作。 无论哪种方式,它在'else'之后失败。 p> div>

change block

if (isset($priceperperson)) {
  $rentalprice = ($priceperperson * $numberofguests * $numberofnights);
 } elseif (!isset($priceperperson)) {
  $rentalprice = $baserentalprice;
 }

to

if (isset($priceperperson) && $priceperperson != '') {
  $rentalprice = ($priceperperson * $numberofguests * $numberofnights);
 } else {
  $rentalprice = $baserentalprice;
 }

isset() will return true if the variable is set but empty (eg. ''). You can use empty() instead.

if (!empty($priceperperson)) { /* ... */ }

Be careful, though. If you are expecting eg. 0 then empty will return true which may not be desired.

Generally, it is recommended to do isset or empty checks first, though. This will prevent warnings from being generated.

You can easily do so with the ternary operator.

$priceperperson = isset($_POST['priceperperson']) ? $_POST['priceperperson'] : '';
$baserentalprice = isset($_POST['rentalprice']) ? $_POST['rentalprice'] : '';
$numberofguests = isset($_POST['numberofguests']) ? $_POST['numberofguests'] : '';

if ($priceperperson) {
    $rentalprice = ($priceperperson * $numberofguests * $numberofnights);
} else {
    $rentalprice = $baserentalprice;
}

You no longer need the isset (or empty) in your if since you already checked that. You can change the condition to $priceperperson != '' if you want to allow eg. 0 as a valid value.

I also changed your elseif for a regular else since the condition was simply inverted.