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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀