PHP table HTML code example

Example 1: php table form

<html>
<body>
<?php 
$username = "username"; 
$password = "password"; 
$database = "your_database"; 
$mysqli = new mysqli("localhost", $username, $password, $database); 
$query = "SELECT * FROM table_name";


echo '<table border="0" cellspacing="2" cellpadding="2"> 
      <tr> 
          <td> <font face="Arial">Value1</font> </td> 
          <td> <font face="Arial">Value2</font> </td> 
          <td> <font face="Arial">Value3</font> </td> 
          <td> <font face="Arial">Value4</font> </td> 
          <td> <font face="Arial">Value5</font> </td> 
      </tr>';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $field1name = $row["col1"];
        $field2name = $row["col2"];
        $field3name = $row["col3"];
        $field4name = $row["col4"];
        $field5name = $row["col5"]; 

        echo '<tr> 
                  <td>'.$field1name.'</td> 
                  <td>'.$field2name.'</td> 
                  <td>'.$field3name.'</td> 
                  <td>'.$field4name.'</td> 
                  <td>'.$field5name.'</td> 
              </tr>';
    }
    $result->free();
} 
?>
</body>
</html>

Example 2: Create a table with PHP in html

<?php
$inputfile = file("prod.txt");

$data_lines = array();
foreach ($inputfile as $line)
{
    $data_lines[] = explode(";", $line);
}

//Get column headers.
$first_line = array();
foreach ($data_lines[0] as $dl)
{
    $first_line[] = explode("=", $dl);
}
$headers = array();
foreach ($first_line as $fl)
{
    $headers[] = $fl[0];
}

// Get row content.
$data_cells = array();
for ($i = 0; $i < count($data_lines); $i++)
{
    $data_cell = array();
    for ($j = 0; $j < count($headers); $j++)
    {
        $data_cell[$j] = substr($data_lines[$i][$j], strpos($data_lines[$i][$j], "=")+1);
    }
    $data_cells[$i] = $data_cell;
    unset($data_cell);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>HTML Table With PHP</title>
    </head>
    <body>
        <table border="1">
            <tr>
            <?php foreach ($headers as $header): ?>
                <th><?php echo $header; ?></th>
            <?php endforeach; ?>
            </tr>
        <?php foreach ($data_cells as $data_cell): ?>
            <tr>
            <?php for ($k = 0; $k < count($headers); $k++): ?>
                <td><?php echo $data_cell[$k]; ?></td>
            <?php endfor; ?>
            </tr>
        <?php endforeach; ?>
        </table>
    </body>
</html>

Tags:

Sql Example