Let's Get Started with a PHP/MySQL Table Page!
- Open Notepad++
- Choose:
File -> New
- Copy the PHP Table Template (PHP) code (below)
- Paste that code into your new file
- Change the put-title-of-this-page-here
- Change these lines:
$query = "_________________________";
$query .= "________;";
to:
$query = "SELECT dish_name, price, is_spicy ";
$query .= "FROM dishes;";
- Click: File -> Save As
- Name your file: \www\table.php
- Change the
Save as type:
to: PHP Hypertext Preprocessor (*.php)
- Click: Save
- Visit your page (http://buffalo.edu/table.php) in your favorite web browser
- Make any changes
- 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 = "cda350"; // 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