[back]

Formatting Data

While the previous exercise allows us to see what info we have in our table, we are limited in how the data can be displayed. Using HTML and PHP, we can easily create a table which offers more flexibility in how it is viewed.

<?php
$username="username";
$password="password";
$database="your_database";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query="SELECT * FROM students";
$result=mysql_query($query);

$num=mysql_numrows($result);
mysql_close();

echo "<b><center>Database Output</center></b><br><br>";
echo "<p>"

?>

<table width=600 border=1>
<tr>
<th>first name</th>
<th>last name</th>
<th>grad year</th>
<th>student number</th>
</tr>


<?php
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$grad_year=mysql_result($result,$i,"grad_year");
$student_no=mysql_result($result,$i,"student_no");
?>

<tr>
<td><? echo "$first"; ?></td>
<td><? echo "$last"; ?></td>
<td><? echo "$grad_year"; ?></td>
<td><? echo "$student_no"; ?></td>
</tr>

<?php
++$i;
}
echo "</table>";

?>

Explanation:

There are two parts to displaying the output inside a table.

The first is setting up the table heads before the loop begins. Since it is not part of the loop, it will not change. I used <th> tags, but regular <td> tags would work just as well.

<table width=600 border=1>
<tr>
<th>first name</th>
<th>last name</th>
<th>grad year</th>
<th>student number</th>
</tr>

The main part of the table is created after the loop. Notice how each piece of PHP is placed inside the HTML table row and column tags.

<tr>
<td><? echo "$first"; ?></td>
<td><? echo "$last"; ?></td>
<td><? echo "$grad_year"; ?></td>
<td><? echo "$student_no"; ?></td>
</tr>

The final piece of PHP is incrementing the loop and closing the table.

<?php

++$i;
}
echo "</table>";

?>

BEYOND THE BASICS

Now that we are outputting this inside a table, we can modify the table in any number of ways.

If we wanted to combine two variables, we could code it as:
<td><? echo "$last, $first"; ?></td>

We could add any HTML attributes to the output as well:
<td><font face="Arial" size="4" color="green"><? echo "$grad_year"; ?></font></td>

Create a new PHP page and save it as display2.php. Make several changes to your output using HTML attributes.