我正在尝试从两个PHP文件中访问一个PHP文件。
insert.php
文件用于将值插入某个表,然后modify.php
文件用于修改表的值。
我想在database.php
中编写两个函数 - 一个用于插入,另一个用于修改。我想将此文件包含在insert.php
和`modify.php
我只想执行database.php
和insert.php
页面调用中的插入函数,并在调用database.php
页面时仅执行modify.php
的修改函数。
有可能这样做吗?
答案 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);