dousi8931 2015-04-20 11:09
浏览 66
已采纳

如何实现可重用的PHP表单处理逻辑?

I am new to PHP and I have a lots of forms in PHP. The forms make use of the standard HTML Input fields and need to be validated on the serverside. How can I implement this, so that I do not have to write lots of boilerplate HTML over and over again, rather only write the minimal amount of code that generate the "full forms". What is the recommended approach to implement this? Thanks.

  • 写回答

2条回答

  • doudanma9706 2015-04-20 11:27
    关注

    If you prefer to do it all yourself, you should at least do it PHP-Classes which will save you from re-writing (if done right ;-)). Handle attributes of the fields through an assoc array, e.g. like this:

    <?php
    
       $form = new Form("MyInput", array ("submit" => "myform.php") );
    
       $form->AddField("input_text", array ("label" => "Your name") );
    
    ?>
    

    To handle validation, you could use attributes such as

       $form->AddField("input_text", array (
            "label" => "Your name" , 
            "validate" => "required"
       ) );
    

    (Only examples, there's a lot of code releated to this which you'd need to write once...)

    That should be useful for learning purposes...

    Next, you could use JS to validate. Pls. note that JS does client-side validation only and you cannot rely on it being executed (user might have turned of JS in his browser), so you still MUST validate in PHP when receiving the data. (And you could use JS-Libraries for that - I've used Parsley and was quite happy with it...)

    If you want to skip that experience, use Frameworks or Templating Engines.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?