开发者

how to call the php function while the page is getting load

I need to call the php function while the page is getting load.

Means when I click a link or menu of the page Homepage.php, then it will redirect to the page called History.php. Here before loa开发者_StackOverflowding the page History.php, it sholud call the function to get the data from the database.

Please spend your valuable time to answer this query. Thanks in advance.


Top of History.php:

<?php
    include('/path/to/php/program/with/function.php');
    the_function();


You can also try at top of:

Hisory.php

<?php 

function getData(){
  // function body  
}

$data = getData();

?>

But if you are using this type of function on many places then you should place it in one file and include it in that file where you want to call this function. As Quentin described.


You are the one sending any response to the browser, so simply call whatever functions prior to sending the rest of the page (do at beginning of PHP page).


The PHP runtime is an interpreter that will "automaticly" (unless configured otherwise) run .php files. This mean that all code within <?php ?> tags will get executed by the PHP engine. So you could place a php code block first in your page. Either directly containing the logic to fetch the data from you server.

Example

// 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);

If you want a persistent connection you use mysql_pconnect() instead of mysql_connect().

I would however strongly encourage you to, at least, put database logic in a class which resides in a separate file which you include using include(), include_once(), require() or require_once().

If this is part of a bigger system and you have the time I would suggest you read up on the MVC pattern and look into a framework like Zend Framework or similar which have good database abstractions etc.

Good luck!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜