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!