如何在操作页面上创建特定的功能来处理表单数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (24)

我有一个models.php包含特定模型的表单规范的页面。

models.php

$books = [
    ['Book Name', 'text' ],
    ['Author', 'text']
];
$vegetables = [
    ['Name', 'text'],
    ['Photo', 'file']
]

现在这个页面被一个admin.php页面访问,该页面HTML form根据给定的nameinput type

我想填写表单并将数据发送到一个handle.php数据库中,并使用特定功能处理这些数据以将数据填充到适当的表格中。

handle.php

function books(){
    // this will fill the details into table of books.
    INSERT INTO BOOKS 
        name = $_POST['book_name']
        author $_POST['author']
}

function vegetables(){
    // this will fill the details into table of vegetables.
    INSERT INTO VEGETABLES 
        name = $_POST['book_name']
        photo = $_FILE['photo']
}
提问于
用户回答回答于

我有一个基本模型,它定义了所有模型需要共同使用的所有方法。这是一个非常简化的版本:

class Model {

    public $modelName = 'default';
    public $id = null;
    private $fields = [];
    private $tableName = 'default';
    private $tableDefinition = [];
    private $idField = 'id';

    public function insert($dataset) {
       // do some database magic by using $this->fields, or $this->tableDefinition
       $sql = "INSERT into {$this->tableName} ...";
       ...
       return $id;
    }
    public function update($id, $dataset) {
        // do some more database magic by using $this->fields, or $this->tableDefinition
    }

    // many more methods. To get data, delete, sort, ..
    //...
}

现在,每个模型都扩展了这个基础模型类,并设置了它的特定参数,甚至可以覆盖某些方法或添加特定的方法:

class Books extends Model {
    public $modelName = 'book';
    private $fields = ['bookName','Author'];
    private $tableName = 'BOOKS';
    private $tableDefinition = [
            ['bookName','varchar'],
            ['Author','varchar']
    ];
    // private $idField = 'id'; // you can ommit that, if it's the default.
}

你可以简单地覆盖一个方法:

class Vegetables extends Model {
    public $modelName = 'vegetable';
    // set all other properties...

    // override insert() for example
    public function insert($dataset) {
        // do something that doesn't comply with the standard procedure
    }
}

然后在handle.php中,你可以做这样的事情:

<?php
$modelName = $request; // get it from your form, your url, ..
                       // & verify this model(file) exists.
$model = new $modelName();
$model->insert($dataSet);

扫码关注云+社区

领取腾讯云代金券