Проверьте ошибки формы перед переходом на страницу действий - PullRequest
0 голосов
/ 06 февраля 2012

Мне нужно проверить ошибки, прежде чем перейти к действию URL формы. Когда я нажимаю «Отправить», он переходит в /test/policy.php, даже если есть ошибки. Я хочу, чтобы он шел туда только в том случае, если в моей форме нет ошибок. Вот мой код:

// Create an empty array to hold the error messages.
$arrErrors = array();
//Only validate if the Submit button was clicked.
if (!empty($_POST['submit']))
 {

      // Each time theres an error, add an error message to the error array
      // using the field name as the key.
      if (empty($_POST['first_name']))
          $arrErrors['first_name'] = '<br><font color="red">Please provide your first name.</font>';
      if (empty($_POST['last_name']))
          $arrErrors['last_name'] = '<br><font color="red">Please provide your last name.</font>';
      if (empty($_POST['business_name']))
          $arrErrors['business_name'] = '<br><font color="red">Please provide your business name.</font>';
 }


      // If the error array is empty, there were no errors.
      // Insert form processing here.

      if (count($arrErrors) == 0)
      {


        $first_name=cleaninput($_POST['first_name']);
        $last_name=cleaninput($_POST['last_name']);
        $business_name=cleaninput($_POST['business_name']);
        //Insert the details into database

      }
      else
      {

        // The error array had something in it. There was an error.
        // Start adding error text to an error string.
        $failure_message= "There was an error in the form";

        $strError="";
        foreach ($arrErrors as $error)
        {
           $strError .= $error;
        }

      }
    }
 ?>



<tr>
   <td>
   <? if(!empty($success_message))
      {
        echo "<center><font color='blue'><b>".$success_message."</b></font><br>";
      }
      if(!empty($failure_message))
      {
         echo "<center><font color='red'><b>".$failure_message."</b></font><br>";
      }
   ?>

<?
if((empty($_POST)) || !empty($strError))
{
     echo "<table align= 'center' width='70%' style='border-top: 1px; border-right: 1px; border-left: 1px; border-bottom: 1px; border-color: black; border-style: solid;'>";
?>
<tr>
  <td>

   <form action="/test/policy.php" method="post">
      <tr height='40'>
         <td>
           <font color="black"><B> First Name: </B></font>
         </td>
     <td><input type="text" size ="40" name="first_name" value="<? if(!empty($strError)) {echo cleaninput($_POST['first_name']);}?>" class="advertising-inputbox-style" />
            <?php if (!empty($arrErrors['first_name'])) echo $arrErrors['first_name']; ?>
     </td>

      </tr>
      <tr height='40'>
         <td><font color="black"><B> Last Name: </B></font></td>
         <td><input type="text" size ="40" name="last_name" value="<? if(!empty($strError)) { echo cleaninput($_POST['last_name']);}?>" class="advertising-inputbox-style"/>
         <?php if (!empty($arrErrors['last_name'])) echo $arrErrors['last_name']; ?>
             </td>
      </tr>

      <tr height='40'>
         <td><font color="black"><B> Email Address: </B></font></td>
         <td><input type="text" size ="40" name="email_address" value="<? if(!empty($strError)) { echo cleaninput($_POST['email_address']);}?>" class="advertising-inputbox-style"/>
         <?php if (!empty($arrErrors['email_address'])) echo $arrErrors['email_address']; ?>
             </td>
      </tr>
       <tr height='35'>
         <td><font color="black"><B> Business Name: </B></font></td>
         <td><input type="text" size ="40" name="business_name" value="<? if(!empty($strError)) { echo cleaninput($_POST['business_name']);}?>" class="advertising-inputbox-style" />
          <?php if (!empty($arrErrors['business_name'])) echo $arrErrors['business_name']; ?>
             </td>
      </tr>

      <tr height='35'>
         <td></td>
         <td><input type="submit" name="submit" value="submit" /></td>
      </tr>

   </form>

  <?}?>
  </td>
   </tr>

</table>

Ответы [ 3 ]

1 голос
/ 07 февраля 2012

Вы можете оставить действие пустым, а затем, после проверки, вы можете перенаправить на /test/policy.php с помощью header.

if (count($arrErrors) == 0) {  
    header('Location: /test/policy.php');  
}
0 голосов
/ 08 февраля 2012

нет, вы не можете использовать POST после перенаправления, но если вам нужно first_name, оно уже есть в базе данных. поэтому отправьте идентификатор пользователя в GET при перенаправлении, например:

//Insert the details into database
your database insert code
$user_id = mysql_insert_id();
....

header('Location: /test/policy.php?user_id='.$user_id);
die();

в policy.php вы выбираете поле пользователя first_name из базы данных

0 голосов
/ 07 февраля 2012

Если приведенный выше код находится в одном файле, то перенаправлять пользователя нужно только в том случае, если ошибок нет. Итак, скажем, этот файл называется index.php, тогда форма будет иметь действие = "index.php" и перейдет к себе после отправки:

<form action="/test/index.php" method="post">

но после того, как вы вставили данные формы пользователя в базу данных, вы перенаправили пользователя в /test/policy.php, например:

//Insert the details into database
your database insert code
....
header('Location: /test/policy.php');
die();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...