简体   繁体   中英

Creating a table in HTML to display the result of a query in MySQL

I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?

  <div id="main">
  <?php
  require_once('../mysqli_connect.php');
  $response = $db->query("SELECT * FROM metabolite");
  echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
  <tr><td align="center"><b>Metabolites</b></td>
  <td align="center"><b>KEGG Id</b></td>
  <td align="center"><b>Synonyms</b></td></tr>';
  while ($data = $response->fetch())
  {
  ?>
  <tr><td align="left">
  <?php echo $data['Metabolite_name']; ?></td>
  <td align="left">
  KEGG: <?php echo $data['Synonyms']; ?></td>
  <td align="left">
  <?php echo $data['Synonyms']; ?></td>
  </tr>
  <?php
  }
  $response->closeCursor();
  ?>
  </div>

I thank you in advance for all your effort and your help.

Tom.

There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.

<?php

function tableCell($content)
{
  echo '<td align="left">'.$content.'</td>';
}

// database access 
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch()) 
{
  // start a row
  echo '<tr>';
    // create the cells
    tableCell($data['Metabolite_name']);
    tableCell('KEGG: '.$data['Synonyms']);
    tableCell($data['Synonyms']);
  // finish a row
  echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();

But this is not worth much, the output should remain the same.

if ($response->num_rows > 0) {
    while($data = $response->fetch_assoc()) {
    echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
        }
    }
else {
    echo "0 results";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM