两个php文件调用一个php并执行不同的功能

时间:2013-09-17 08:49:44

标签: php mysql

我正在尝试从两个PHP文件中访问一个PHP文件。

insert.php文件用于将值插入某个表,然后modify.php文件用于修改表的值。

我想在database.php中编写两个函数 - 一个用于插入,另一个用于修改。我想将此文件包含在insert.php和`modify.php

我只想执行database.phpinsert.php页面调用中的插入函数,并在调用database.php页面时仅执行modify.php的修改函数。

有可能这样做吗?

2 个答案:

答案 0 :(得分:1)

<强> database.php中

<?php
function insert_fn()
{
//write insert code here
echo "inserted"; //just for demo.
}
function modify_fn()
{
//write modifycode here
echo "modified."; //just for demo.
}
?>

<强> insert.php

<?php
include("database.php");
insert_fn();
?>

<强> modify.php

<?php
include("database.php");
modify_fn();
?>

答案 1 :(得分:0)

您可以使用上述两个函数创建database.php文件:function update()function insert()

然后使用php include将database.php文件包含到其他两个文件中,如下所示:

insert.php

include_once('database.php');
insert(your data comes here);

modify.php

include_once('database.php');
update(your data comes here);

您应该在拥有模型的数据库层中创建数据库层,并为此使用类的实例。然后,将database.php包含到其他脚本中,并实例化db对象并调用方法。像这样:

database.php中

class MyDatabaseThingy 
{
    /* rest of your code */
    public function update(data) {your code here}
    public function insert(data) {your code here}
    /* rest of your code */
}

insert.php

include_once(database.php);
$dbObj = new MyDatabaseThingy();
/* make sure you have the connection and so on */
$dbObj->insert(your data);

modify.php

include_once(database.php);
$dbObj = new MyDatabaseThingy();
/* make sure you have the connection and so on */
$dbObj->update(your data);