Let's Get Started with a PHP/MySQL Table Page!

  1. Open Notepad++
  2. Choose: File -> New
  3. Copy the PHP Table Template (PHP) code (below)
  4. Paste that code into your new file
  5. Change the put-title-of-this-page-here
  6. Change these lines:
    $query = "_________________________";
    $query .= "________;";

    to:
    $query = "SELECT dish_name, price, is_spicy ";
    $query .= "FROM dishes;";
  7. Click: File -> Save As
  8. Name your file: \www\table.php
  9. Change the Save as type: to: PHP Hypertext Preprocessor (*.php)
  10. Click: Save
  11. Visit your page (http://buffalo.edu/table.php) in your favorite web browser
  12. Make any changes
  13. Save your changes

PHP Table Template (PHP)

<!doctype html>
<html>
  <head>
    <title>put-title-of-this-page-here</title>
  </head>
  <body>
  <?php
  $dbUsername = "your-localhost-username"; // probably 'root'
  $dbPassword = "your-localhost-mysql-password"; // probably ''
  $dbDatabase = "mfc211"; // localhost database name
  $dbServer   = "localhost";
  // Create a new server connection
  $dbConn = new mysqli($dbServer, $dbUsername, $dbPassword, $dbDatabase);
  // Create the query
  $query  = "____________________________";
  $query .= "_______________";
  // Send the query to MySQL
  $result = $dbConn->query($query,MYSQLI_STORE_RESULT);
  $row_cnt = $result->num_rows;
?>
<?php
  printf("<h2> My Dish Table Has %d Rows!</h2><br>\n", $row_cnt);
  // the <<< _END through the _END in the next lines 
  // demonstrate the PHP HEREDOC statement
  $table = <<< _END
     <table>
       <thead>
         <tr>
           <th>Dish</th>
           <th>Price</th>
           <th>Spicy</th>
         </tr>
       </thead>
       <tbody>
_END;
  // Iterate through the result set
  while (list($name, $price, $isSpicy) = $result->fetch_row()) {
    $table .= "  <tr class='evenRow'>\n";
    $table .= "      <td style='text-align: center;'>$name</td>\n<td>\$$price</td>\n<td>";
    if ($isSpicy == 1) {
      $table .= "Yes";
    } else {
      $table .= "No";
    }
    $table .= "</td>\n";
    $table .= "</tr>\n";
  }
  $table .= "</tbody>\n</table>\n";
  echo($table);
  // Close the database server connection
  $dbConn->close();
?>
  </body>
</html>

Output