If you’re programming directly in PHP, here’s a simple example of displaying records using PHP in HTML. This PHP is for PHP 5.1 and later, and requires the mysql PDO module be installed. Most web providers that provide PHP will include the mysql module.
<html>
<head>
<title>My Albums</title>
</head>
<body>
<h1>My Albums</h1>
<table>
<tr><th>Album</th><th>Artist</th><th>Year</th><th>Rating</th></tr>
<?
$host = '127.0.0.1'; //or $host = 'localhost';
$user = 'Username';
$pass = 'Password';
$database = 'music';
$query = "SELECT album, artist, year, rating FROM albums ORDER BY artist";
try {
$dbh = new PDO("mysql:host=$host;dbname=$database", $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $dbh->query($query);
while ($album = $results->fetch()) {
albumRow($album);
}
$dbh = null;
} catch (PDOException $error) {
echo "Problem connecting to $host: ", $error->getMessage();
die();
}
function albumRow($albumInfo) {
$album = $albumInfo['album'];
$artist = $albumInfo['artist'];
$year = $albumInfo['year'];
$rating = $albumInfo['rating'];
echo "\t\t\t<tr>";
echo "<th>$album</th><td>$artist</td><td>$year</td><td>$rating</td>";
echo "</tr>\n";
}
?>
function albumRow($albumInfo) {
$album = $albumInfo['album'];
$artist = $albumInfo['artist'];
$year = $albumInfo['year'];
$rating = $albumInfo['rating'];
echo "\t\t\t<tr>";
echo "<th>$album</th><td>$artist</td><td>$year</td><td>$rating</td>";
echo "</tr>\n";
}
?>
</table>
</body>
</html>
The mysql_connect() function connects your page to the database, the mysql_select_db() function selects the database you want, and the mysql_query() function performs your query. The mysql_free_result() function tells PHP that you’re finished with that query and the mysql_close() function tells PHP that you’re finished with that connection.
The important parts are mysql_error(), which tells you the last error that occurred, and mysql_fetch_array(), which gives you the next row from the database. Items in the row can be pulled out by their name.