Databases Reference
In-Depth Information
This produces the following output:
1 New Order
2 Nick Cave & The Bad Seeds
3 Miles Davis
4 The Rolling Stones
5 The Stone Roses
6 Kylie Minogue
You can see that the
artist_id
column is output by printing the first element of the
array
$row
by referencing
$row[0]
. The
artist_name
is output by referencing
$row[1]
.
Note that we enclosed the output in HTML
<pre>
tags; if we hadn't, the browser would
have ignored the newline (
\n
) character during display. You could still have used your
browser's View Source option to see the lines as they were sent to the browser by the
PHP script.
Consider another example from the
music
database. This time, let's examine the struc-
ture of the
artist
table:
mysql>
DESCRIBE artist;
+-------------+-----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+-------+
| artist_id | int(5) | | PRI | 0 | |
| artist_name | char(128) | YES | | NULL | |
+-------------+-----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
The following code fragment selects all rows from the
artist
table and prints the col-
umns after a call to
mysql_fetch_array( )
. In this example, rather than explicitly print-
ing the individual elements, we print all elements of the row starting with the first:
// Tell the browser to expect preformatted text
print "<pre>";
// Run the query on the connection
if (!($result = @ mysql_query("SELECT * FROM artist", $connection)))
die("Couldn't run query");
// Count the number of columns in the results
$count = @ mysql_num_fields($result);
// Until there are no rows in the result set, fetch a row into
// the $row array.
while ($row = @ mysql_fetch_array($result))
{
print "\n";
// Print out the columns
for($x=0; $x<$len; $x++)
print "{$row[$x]} ";
}
// Tell the browser that the preformatted text has ended
print "</pre>";