<html>
<!--
==========================================================================================
This PHP script retrieves data from a database (table: cust_order)
==========================================================================================
-->
<head>
<title>Retrieve data from database</title>
<style>
a {text-decoration:none; color:brown}
table {font:10pt arial; border:solid 2px black; border-collapse:collapse; margin-left:70px; background-color:#eeeeee; }
th,td {border:solid 1px black; padding-left:5px; padding-right:5px; vertical-align:top;}
</style>
</head>
<body bgcolor=lightyellow>
<h1><center>The Ice Cream Shop</center></h1>
<h2>Retrieve data from Database</h2>
<?php
$host = 'localhost'; #local (either PC or NYU server)
$data = array(); #define an array
read_data();
display();
//===============================================================================
function read_data()
{
global $host, $data;
$host_port = $host;
$DBname = 'demo2';
$DBuser = 'demo2';
$DBpswd = 'demo2';
try {
$connect = mysqli_connect($host_port,$DBuser,$DBpswd,$DBname); #connect to db server
}
catch(Exception $e) {
// die('Could not connect: ' . $e->getMessage());
die('Could not connect: ' . mysqli_connect_error());
}
$query = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id
FROM cust_order
ORDER BY order_id";
//print $query; #for debugging
$cursor = mysqli_query($connect,$query); #execute the query
if (! $cursor)
die('Could not execute query: ' . mysqli_error($connect));
$i=0;
while ($row = mysqli_fetch_array($cursor)) #get each row as an array
$data[$i++] = $row; #store row in 2 dim array
mysqli_free_result($cursor); #free result buffer
mysqli_close($connect); #close connection
}
//===============================================================================
function display()
{
global $data;
print "<table>
<tr bgcolor=tan>
<th>Order#<th>Name<th>Address<th>Flavors<th>Toppings<th>Credit Card \n";
foreach($data as $row)
{
$first = $row['firstname'];
$last = $row['lastname'];
$address = $row['address'];
$flavor = $row['flavor'];
$topping = $row['topping'];
$creditCard = $row['creditCard'];
$order_id = $row['order_id'];
$address2 = nl2br($address); #change all \n to <br>
$flavor2 = str_replace("," , "<br>", $flavor);
$topping2 = str_replace("," , "<br>", $topping);
print "<tr>";
print "<th>$order_id</th> <td>$first $last </td> <td>$address2 </td>
<td>$flavor2 </td> <td>$topping2 </td> <td>$creditCard</td> \n";
}
print "</table> \n";
}
//===============================================================================
?>
<?php include "../include.php"; ?> <!-- hyperlink to see the code -->
</body>
</html>