简体   繁体   English

如果所有内容都以表格填写,请转到PHP中的新页面

[英]If everything is filled in form go to new page in PHP

I have a problem, I want to make form and I want to check it with php script if it's filled. 我有一个问题,我想制作表格,我想用PHP脚本检查它是否填写。 I found a solution, but Is there any other way(more 'professional') to make it. 我找到了一个解决方案,但还有其他方法(更“专业”)来实现它。 Here is my code now: 这是我现在的代码:

$x = 0;
    if(empty($name)){
    $nameKL = "No name";
    } else {
    $x = $x + 1;
    }

    if(empty($price)){
    $priceKL = "No price";
    } else {
    $x = $x + 1;
    }

    if($x == 2){
    header('Location: nextpage');
    }

So the Idea is: If checked variable is not empty I give x=x+1 , If its empty I return error. 所以理念是:如果检查变量不为空,我给x=x+1 ,如果它为空我返回错误。 I have two fields in form, so If x==2 everything is okay. 我有两个字段,所以如果x==2一切都没问题。 else errors are echo'ed in html form. else错误echo'edhtml形式。 So is there any smarter way to do this? 那么有没有更智能的方法呢? I can't think out any on my own... 我自己也想不出来......

PS. PS。 It's only part of my code, and I need help only with this logical part 它只是我代码的一部分,我只需要这个逻辑部分的帮助

Make an array of elements. 制作一个元素数组。

<input type="text" name="formadata['fname']" />
<input type="text" name="formadata['lname']" />
<input type="text" name="formadata['age']" />

in PHP you can loop all elements 在PHP中,您可以循环所有元素

$inputs = $_POST['formdata'];
$errors = array(
              'fname' => 'First name message',
              'lname' => 'Last name message',
              'age' => 'Age message',
          );
foreach($inputs as $input) {
    if(empty($input)) return $errors[$input];
}

So this way you can manage to check whether input is empty or not in PHP 因此,您可以通过这种方式在PHP中检查输入是否为空

Using Ternary Operation. 使用三元运算。 Please check below simple code. 请查看下面的简单代码。

$x = 0;
$nameKL = empty($name) ? "No name" : $name;
$priceKL = empty($price) ? "No price" : $price;


if($nameKL && $priceKL){
header('Location: nextpage');
}
$nameKL = empty($name) ? "No name" : $name;
$priceKL = empty($price) ? "No price" : $price;


if(empty($name) && empty($price)) {
    header('Location: nextpage');
}

Well, I found the solution on my own. 好吧,我自己找到了解决方案。 I set up a variable that has a true value at the beginning and then: 我设置了一个在开头有一个true值的变量然后:

$validate = true;

if(empty($name)){
$nameKL = "no name";
$validate = false;
}

if(empty($price)){
$priceKL = "no price";
$validate = false;
}


if($validate == true){
header('Location page.php');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM