album.php 1.86 KB
Newer Older
Sorrel Harriet's avatar
Sorrel Harriet committed
1
2
3
4
5
6
7
<?php

// open a new MySQL database connection

// define a connection 'handle'
$link = mysqli_connect(
    'localhost',
Sorrel Harriet's avatar
Sorrel Harriet committed
8
9
10
    'USERNAME',
    'PASSWORD',
    'DATABASE_NAME'
Sorrel Harriet's avatar
Sorrel Harriet committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
);

// check connection succeeded
if (mysqli_connect_errno()) {
    exit(mysqli_connect_error());
}

// define the SQL query to run (from lab 3 queries.sql!)
// use column aliases if necessary to make referencing fields in result-set easier
$sql = "SELECT t.name AS track, t.track_number, a.title AS album
FROM Track t
INNER JOIN Album a
    ON t.album_upc=a.upc
WHERE a.upc='018274372722'
ORDER BY track_number ASC";

// query the database
$result = mysqli_query($link, $sql);

// define a variable for HTML content string
$content = "";

// get number of rows in result-set
$row_cnt = mysqli_num_rows($result);

// check if there are rows to display...
if ($row_cnt == 0) {
	// if not, output a suitable message
	$content .= "<p>The album you requested was not found!</p>";
} else {
	// otherwise, update the HTML in $content

	// get a single row from the result-set as an enumerated array
	$row = mysqli_fetch_row($result);
	// reference the first item in the array by index
	$content .= "<h1>".$row[0]."</h1>";
	$content .= "<table cellpadding='4' border='1'>
					<thead align='left'>
						<tr>
							<th>Track name</th>
							<th>Track number</th>
						</tr>
					</thead>
					<tbody>";
    // while there are rows, fetch each row as an associative array
    while ($row = mysqli_fetch_assoc($result)) {
		// append the content with more HTML containing row data
		$content .= "<tr>
						<td>".$row['track']."</td> 
						<td>".$row['track_number']."</td>
					</tr>"; // reference a field value in the array by its key!
    }
    // free result set
    mysqli_free_result($result);

	$content .= "</tbody></table>";
}

// close the connection to the database */
mysqli_close($link);

// output the HTML

echo $content;

Sorrel Harriet's avatar
Sorrel Harriet committed
76
?>