开发者

Reusable functions with PHP

开发者 https://www.devze.com 2023-04-13 01:35 出处:网络
I have two functions addCategory, and addArticle as follows : function addCategory(){ $title=$_POST[\'title\'];

I have two functions addCategory, and addArticle as follows :

function addCategory(){

$title=$_POST['title'];
$description=$_POST['description'];
$photo=$_FILE['photo'];

$cmd='INSERT INTO tbl_categ(title开发者_如何学JAVA,description,photo)VALUES(:title,:description,:photo)';

$stmt=$pdo->prepare($cmd);
$stmt->bindParam(':title',$title);
$stmt->bindParam(':description',$description);
$stmt->bindParam(':photo',$photo);

$stmt->execute();
}

and this is the function addArticle:

function addArticle(){

$title=$_POST['title'];
$id_categ=$_POST['id_categ'];
$texte=$_POST['texte'];
 $keywords=$_POST['keywords'];
$photo=$_FILE['photo'];

$cmd='INSERT INTO tbl_categ(id_categ,title,texte,keywords,photo)VALUES(:id_categ,:title,:texte,:keywords,:photo)';

$stmt=$pdo->prepare($cmd);
$stmt->bindParam(':id_categ',$id_categ);
$stmt->bindParam(':title',$title);
$stmt->bindParam(':texte',$texte);
$stmt->bindParam(':keywords',$keywords);
$stmt->bindParam(':photo',$photo);

$stmt->execute();
}

As you can see, those two functions are doing the same task but with different tables... it's about an "Add" action... so my goal is to make just one add function which will be working for every "adding" action whatever is it's number of POST parameters (coming from forms) , whatever is the number of fields in the table, and whatever is the table in the database.

I've got an idea about adding a parameter to this function, which will define the name of the table where the data will be stored , and every form has his own table name, But how can the function determine the number of table's fields , and the names of those fields to use them in the command string?

Thank you in advance


You can determine the table's fields by using DESCRIBE TABLE. After that, you might find it cleaner to store this in a class, instead of having a lot of global variables floating around.

After that, you might want to optimize by caching the DESCRIBE TABLE results, so you don't have to grab them each time.

After that, you might realize that you have essentially recreated what most Active Record type libraries try to do, and you're better off just using one of those.

Doctrine is a good choice (although it uses code generation instead).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号