Categories
MySQL PHP Snippet

Quick and Dirty: List records in a table using PHP and MySQL

This code lists reads a dataset from the database and lists all attributes in a table. 

This code sample is deliberately quite basic, though CSS is used (through the $bgcolour variable) to create alternating background colours for the rows.

The code assumes you have already connected to a database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
echo "<table border='0'>";
// capture the data
$dataset = mysql_query("SELECT * FROM tablename");
// now process the dataset, one row at a time
while ($row = mysql_fetch_assoc($dataset)) {
  // create a variable for each attribute in the record
  //  - variables are easier to use when building the table 
  foreach($row as $var => $value) {
    $$var = $value;
  }
  // set the alternating background colour for the row
  $bgcolour = (!isset($bgcolour) || $bgcolour == "#F0F7FF") ? "#FFFFFF" : "#F0F7FF";
  // build the rows, placing the variables in <td> elements as appropriate
  echo "\n<tr style="background-color:$bgcolour;">";
  echo "\n<td style="font-size:80%;">$attribute</td>";
  echo "\n</tr>";
} // end while
echo "</table>";

Leave a Reply