Page 21 - Open Soource Technologies 304.indd
P. 21
Unit 1: Introduction to PHP
The code in the Example connects to the database, issues a query to match up movies with the Notes
actor’s name, and produces a table as output. It uses the DB library to access a MySQL database,
issue a query, and display the results. The <? = and?> bracketing construct runs PHP code and
prints the result.
Querying the Bond database
<html>
<head>
<title>Bond Movies</title>
</head>
<body>
<table border=1>
<tr><th>Movie</th><th>Year</th><th>Actor</th></tr>
<?
php // connect require_once(‘DB.php’);
$db = DB::connect(“mysql://username:password@server/webdb”);
if (DB::iserror($db))
{
die($db->getMessage( ));
} // issue the query $sql = “SELECT movies.title,movies.year,actors.name FROM movies,actors
WHERE movies.actor=actors.id ORDER BY movies.year ASC”;
$q = $db->query($sql);
if (DB::iserror($q))
{
die($q->getMessage( ));
} // generate table
while ($q->fetchInto($row))
{
?>
<tr><td><?= $row[0] ?></td> <td><?= $row[1] ?></td> <td><?= $row[2] ?></td> </tr>
<?php
}
?>
</table>
</body>
</html>
LOVELY PROFESSIONAL UNIVERSITY 15