首页 > 解决方案 > 为什么我的 PHP 错误消息不能正常工作?

问题描述

我正在创建一个基本表格来购买成人和儿童票。通过表单的设置方式,用户必须购买成人票,但不需要购买儿童票。我添加了一些错误消息/验证以在表单中强制执行规则。所有成人票错误消息都可以正常工作,但儿童票错误消息无法正常工作。

我希望儿童票规则检查以下内容:输入了有效数字(也不是字母),数量大于 0,并且输入了整数。我以为我已经设置了规则,所以他们只在子票输入不为空时才开始验证,但他们仍在尝试验证何时为空,考虑到没有子票需要,我不希望它这样做被购买。我怎样才能让它正常工作?

这是我的带有错误消息的 PHP 代码。

<?php
  $adult=$_POST['adult'];
  $child=$_POST['child'];
  $date=date('m/d/Y');

  function isInteger($input) {
    return(ctype_digit(strval($input)));
  }
  if (empty($adult)) {
    $error_message='You must purchase at least 1 Adult ticket!';
  }
  else if (!is_numeric($adult)) {
    $error_message="You must enter a valid number!";
  }
  else if ($adult <= 0) {
    $error_message="You must enter a quantity greater than zero!";
  }
  else if (!isInteger($adult)) {
    $error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
  }
  else if (!empty(!is_numeric($child))) {
    $error_message="You must enter a valid number!";
  }
  else if (!empty($child <= 0)) {
    $error_message="You must enter a quantity greater than zero!";
  }
  else if (!empty(!isInteger($child))) {
    $error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
  }
  else if ($adult + $child > 5) {
    $error_message="Sorry, there is a limit of 5 total tickets per customer!";
  }
 else {
$error_message='';
  }
  if($error_message !=""){
    include('index.php');
    exit();
  }
?>

标签: php

解决方案


如果$child = 1

if(!empty($child <= 0) )相当于if(!empty(false))which 没有意义。

(!empty(!is_numeric($child)))

if(isset($child) && $child <= 0) {}改为使用

你也可以使用$child = isset($_POST['child']) ? $_POST['child'] : 0


推荐阅读