PHP将服务器代码与HTML输出混合

时间:2009-12-21 05:14:59

标签: php html class

我正在编写一个小脚本,它将获取表单数据并对其执行某些操作。如果失败,则再次显示错误和表单。如果成功,它将显示成功消息。

后端代码使用的类如果表单数据出错则会抛出异常。对类的调用将包含在try {} catch {}中。

两次显示表单的最佳方式是什么?

我需要类似的东西:

If form submitted: 

   Try:
      Add the account via class
   Catch:
      Echo the error
      Show the form 

   Echo succcess

Else:
   Show the form

3 个答案:

答案 0 :(得分:2)

对于简单的表格,我这样写:

<?php

   if (isset($_POST['submit']))
   {
   $errorFound=0;

   if (empty($_POST['form_variable']))
   { 
     $errorFound=1; 
     $error_str="empty string";
   }

   if (!$errorFound) // if no errors, process the form!
   { 
   //process whatever you do with it - redirect to another page
   }

  }
 ?> 
 <form action="name.php">
 <div> <input name='form_variable'> 
 <?php if ($errorFound) {echo $error_str} ?>
 </div> 
 <input type=submit name=submit>
 </form> 

如果它从未提交过,它将直接转到html表单并显示但是如果你提交并且出现错误,则会导致php在输入标记之后再次显示带有echo'd error_st的表单。

答案 1 :(得分:1)

在变量中对表单的HTML进行编码,并在两个位置回显变量。

$form = "<form>...</form";

if ($_POST) {
  if (addAccount($fname,$email)) {
    print "Success";
  } else {
    print "Errors";
    print $form;
  }
} else {
  print $form;
}

答案 2 :(得分:1)

你可以使用smarty之类的模板引擎轻松完成所有这些工作。它与您的问题完全相同

{如果$ form eq提交了}}

{if $ success}       通过课程添加帐户    {其他}       回应错误       显示表格

回声成功    {/如果}   {其他}    显示表格 {/如果}

或者,如果你只是想在php中单独使用,那么只需要执行“netrox”方法即可。很好。

这些是在php中调用heredoc的另一个概念。你可以用非常简单的方式在PHP中包含你的html。

相关问题