我需要在页面正在加载时调用php函数。如何在页面正在加载时调用php函数
意思是当我点击页面Homepage.php的链接或菜单时,它会重定向到名为History.php的页面。 这里在加载页面History.php之前,它会调用函数从数据库中获取数据。
请花你宝贵的时间回答这个问题。提前致谢。
我需要在页面正在加载时调用php函数。如何在页面正在加载时调用php函数
意思是当我点击页面Homepage.php的链接或菜单时,它会重定向到名为History.php的页面。 这里在加载页面History.php之前,它会调用函数从数据库中获取数据。
请花你宝贵的时间回答这个问题。提前致谢。
顶History.php的:
<?php
include('/path/to/php/program/with/function.php');
the_function();
你是一个发送到浏览器的任何回应,所以干脆叫什么之前,发送页面的其余部分功能(在做PHP页面的开始)。
您也可以尝试在顶部:
Hisory.php
<?php
function getData(){
// function body
}
$data = getData();
?>
但如果您使用的是许多地方这种类型的函数,那么你应该把它放在一个文件,包括它在那个你想调用这个函数的文件中。如昆汀所述。
PHP运行时是一个将“自动”(除非另有配置)运行.php
文件的解释器。这意味着<?php ?>
标签中的所有代码都将由PHP引擎执行。所以你可以先在你的页面放置一个php代码块。直接包含从您的服务器获取数据的逻辑。
例
// Example code taken from php website
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
mysql_close($link);
如果你想有一个持久连接使用mysql_pconnect()
,而不是mysql_connect()
。
我不过强烈建议您,至少,把数据库逻辑驻留在一个单独的文件,你包括使用include()
,include_once()
,require()
或require_once()
类。
如果这是一个更大的系统的一部分,你有时间我会建议你在MVC模式念起来看看像Zend框架或类似的框架具有良好的数据库抽象等
好运!
如果您打电话给History.php,PHP将运行。无论您需要运行哪些代码来获取数据,您都会在那里完成。为什么这是不够的?或者你的意思是别的吗? – 2011-05-24 06:06:00
由于PHP在加载页面之前运行,只需在history.php中调用你的函数 – JohnP 2011-05-24 06:06:32
是@Pekka,但我需要调用一个函数,在History.php页面下载(执行)之前应该执行该函数。 – Indu 2011-05-24 06:08:36