如果字段为空,则重定向到php页面

时间:2011-08-07 08:48:28

标签: php forms validation redirect

我想在用户提交没有任何参数的表单时重定向到有表单的页面,我也想返回错误信息,如何从控制器重定向到表单?

<form action="controllers/Customer.controller.php" method="post">

    <label for="cellPhoneNo">cell phone number</label>
    <input type="text" name="cellPhoneNo" class="textField"/>

    <label for="telephone">telephone number</label>
    <input type="text" name="telephone" class="textField"/>

    <input type="submit" name="searchCustomer" value="بحث"/>
</form>

这里是Customer.controller.php页面

  if(trim($_POST['cellPhoneNo']) == "" && trim($_POST['telephone']) ==""){

  //include('Location:index.php'); //what I supposed to write here?
   echo "empty";
}

2 个答案:

答案 0 :(得分:2)

<?php
session_start();

if(isset($_POST)){
    $cont=true;
    //cellPhoneNo
    if(!isset($_POST['cellPhoneNo']) || strlen($_POST['cellPhoneNo'])< 13){ //13 being the telephone count
        $cont=false;
        $_SESSION['error']['cellPhoneNo']='Cell phone is required & must be 13 in length';
        header('Location: ./index.php');
        die();
    }
    //telephone
    if(!isset($_POST['telephone']) || strlen($_POST['telephone'])< 13){ //13 being the telephone count
        $cont=false;
        $_SESSION['error']['telephone']='Telephone is required & must be 13 in length';
        header('Location: ./index.php');
        die();
    }

    if($cont===true){
        //continue to submit user form

    }else{
        header('Location: ./index.php');
        die();
    }
}else{
    header('Location: ./index.php');
}
?>

答案 1 :(得分:1)

不知道框架的结构,你可以使用php的header

if(trim($_POST['cellPhoneNo']) == "" && trim($_POST['telephone']) ==""){

   $_SESSION['error'] = 'Fields cannot be empty!';
   header('Location: myformlocation.php');
   exit(); 
}

就在你的表格上方:

<?php if(isset($_SESSION['error'] )) : ?>

<div class="error"><?php echo $_SESSION['error'];?></div>

<?php 
unset($_SESSION['error']); 
endif; ?>


<form action="controllers/Customer.controller.php" method="post">

因此,每当表单提交时,如果字段为空,则重新加载表单页面,并且由于现在设置了$ _SESSION错误,因此将显示该表单。您可能希望使用$ _SESSION ['error']显示一个函数,因此您不会在每个表单中编写所有代码。

评论后编辑:
嗯,我真的不太明白你的问题,你可以使用$ _GET:

header("Location: ../index.php?page=customerSearch"); 

并在索引中检索它 $pageToInclude = $_GET['page']; //正确消毒

或使用

$_SESSION['pageToInclude'] = 'CustomerSearch'; 
$_SESSION['error'] = 'Fields cannot be empty!';
header('Location: myformlocation.php');
....

并在索引中使用

$pageToInclude = isset($_SESSION['pageToInclude']) ? $_SESSION['pageToInclude'] : 'someotherdefaultpage';