You are on page 1of 7

Performing Database Queries

Sapna Rajan

Topics
HTML Tables and Database Tables
Complex Mapping -Multiple queries Versus complex printing

HTML Tables and Database Tables


One-to-One Mapping Focus on printing out the tables and queries in such a way that each database field prints in its own HTML column. The simplest case of displaying a table is the one in which the structure of a database table or query does correspond to the structure of the HTML table we want to display.

<html><head><title>MySQL Table Viewer</title></head><body> <?php $db_host = 'localhost'; $db_user = 'sapna'; $db_pwd = 'sapna'; $database = 'db'; $table = 'country'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database");

// sending query $result = mysql_query("SELECT * FROM {$table}"); if (!$result) { die("Query to show fields from table failed"); } $fields_num = mysql_num_fields($result); echo "<h1>Table: {$table}</h1>"; echo "<table border='1'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td>{$field->name}</td>"; } echo "</tr>\n";

// printing table rows while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>\n";

} mysql_free_result($result); ?> </body></html>

Complex Mapping
A multiple-query example Complex printing of data

You might also like