【问题标题】:PHP Mixing server code with HTML outputPHP 混合服务器代码和 HTML 输出
【发布时间】:2010-12-28 15:25:01
【问题描述】:

我正在编写一个小脚本,它将获取表单数据并对其进行处理。如果失败,它会再次显示错误和表单。如果成功,它将显示一条成功消息。

后端代码使用的类会在表单数据出现错误时引发异常。对类的调用将包装在 try{} catch{} 中。

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

我需要类似的东西:

If form submitted: 

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

   Echo succcess

Else:
   Show the form

【问题讨论】:

    标签: php html class


    【解决方案1】:

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

    <?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 再次显示表单.

    【讨论】:

      【解决方案2】:

      将表单的 HTML 编码到一个变量中,并在两个位置回显该变量。

      $form = "<form>...</form";
      
      if ($_POST) {
        if (addAccount($fname,$email)) {
          print "Success";
        } else {
          print "Errors";
          print $form;
        }
      } else {
        print $form;
      }
      

      【讨论】:

      • 我在想这就是要走的路
      • 您甚至可能更喜欢表单变量声明的 HEREDOC 语法,以使 HTML 更具可读性。见:php.net/manual/en/…
      【解决方案3】:

      您可以使用类似模板引擎的 smarty 轻松完成所有这些工作。它和你的问题完全一样

      {如果提交了 $form eq)}

      {如果$成功} 通过类添加帐户 {别的} 回显错误 显示表格

      回声成功 {/如果} {别的} 显示表格 {/如果}

      或者,如果您只想在 php 中执行此操作,则只需执行“netrox”方法即可。挺好的。

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

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2011-01-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多