<html>
<head>
<title>Persistent Connection</title>
<style>
a {text-decoration:none; color:blue}
table {font-family:arial; font-size:11pt}
</style>
</head>
<body bgcolor=lightyellow>
<h1><center>The Ice Cream Shop</center></h1>
<h2>Retrieve data from database - with Persistent connection</h2>
<?php
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE); #all but warnings & notices
$host = 'localhost'; #local (either PC or NYU server)
$data = Array(); #define an array
read_data();
display();
//===============================================================================
function read_data()
{
global $host, $data;
$host = $host;
$DBname = 'demo2';
$DBuser = 'demo2';
$DBpswd = 'demo2';
#open persistent connection
$connect = mysqli_connect('p:'.$host,$DBuser,$DBpswd,$DBname); #if open from previous call
#use the same connection
#connection is auto closed
#after x seconds (ini.php)
if (! $connect)
die('Could not connect: ' . mysqli_connect_error());
$sort = $_GET['sort'];
$seq = $_GET['seq'];
if (!$sort) $sort = "lastname";
$query = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id
FROM cust_order
ORDER BY lower($sort) $seq"; #not case sensitive
//print $query; #for debugging
$cursor = mysqli_query($connect,$query); #execute the query
if (! $cursor)
die('Could not execute query: ' . mysqli_error($connect));
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
}
//===============================================================================
function display()
{
global $data;
$seq = $_GET['seq'];
$seq = ($seq == 'asc') ? 'desc' : 'asc'; //switch sort ASC for DESC
print "<table bgcolor=#eeeeee border=5 width=800 outset>
<tr bgcolor=tan>
<th>Order#</th>
<th><a href=$_SERVER[PHP_SELF]?sort=lastname&seq=$seq >Name</a>
<th><a href=$_SERVER[PHP_SELF]?sort=address&seq=$seq >Address</a>
<th><a href=$_SERVER[PHP_SELF]?sort=flavor&seq=$seq >Flavors</a>
<th><a href=$_SERVER[PHP_SELF]?sort=topping&seq=$seq >Toppings</a>
<th><a href=$_SERVER[PHP_SELF]?sort=creditCard&seq=$seq>Credit Card</a> \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 valign=top>";
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>