Logo  

CS479/579 - Web Programming II

Displaying exercises/e9/solution/component.php

<?php
if (isset($_GET['cid'])) {
  $cid = (int)$_GET['cid'];
} else header("location:store.php");
$vid = isset($_GET['vid'])? (int)$_GET['vid'] : null;

$myconn = new mysqli("localhost", "sbaker", "sbaker", "sbaker");
function getvendor($vid) {
  global $myconn;
  $st = $myconn->prepare("SELECT name FROM vendor WHERE vid=?");
  $st->bind_param("i", $vid); $st->bind_result($name);
  $st->execute(); $st->fetch(); $st->close();
  return $name;
}
?>
<!DOCTYPE html>
<html>
<head>
 <title> Store front </title>
 <meta charset='utf-8'>
 <link rel=stylesheet type='text/css' href='style.css'>
</head>
<body>
<table id='ctbl'>
<tr>
  <td colspan=2 id='top'><a href='store.php'>Very Generic Super Computer Store</a><br>&nbsp;
<tr>
<td id='sidelist'>
<ul>Vendors
<?php
$st = $myconn->prepare("SELECT vid, name FROM vendor WHERE vid IN
     (SELECT DISTINCT vid FROM inventory WHERE cid = ?) ORDER BY name ASC")
  or die("select:".$myconn->error . "\n");
$st->bind_param("i", $cid);
$st->bind_result($id, $name);
$st->execute();
while($st->fetch()) {
  echo "<li><a href='component.php?cid={$cid}&vid={$id}'> $name </a>\n";
}
$st->close();
?>
</ul>
<td id='items'>
<h1><?php
  $st = $myconn->prepare("SELECT name FROM component WHERE cid = ?");
  $st->bind_param("i", $cid);
  $st->bind_result($name);
  $st->execute();
  $st->fetch();
  $st->close();
  echo "$name";
?></h1>
<table style='margin: 0 auto;'>
<?php
function show($item) {
  $vendor = getvendor($item['vid']);
  $price = '$'.$item['price'];
  echo <<<DESC
<a href='item.php?iid={$item['iid']}'>
<table class='item'>
<tr>
 <td class='pic'> {$item['description'][0]}
 <td class='desc'> <div class='vendor'>$vendor</div> {$item['description']}<br>
   <div class='price'>{$price}</div>
</table>
</a>
DESC;
}
$items = [];
if ($vid != null) {
  $st = $myconn->prepare("SELECT * FROM inventory WHERE cid = ? AND vid = ? LIMIT 20");
  $st->bind_param("ii", $cid, $vid);
} else {
  $st = $myconn->prepare("SELECT * FROM inventory WHERE cid = ? LIMIT 20");
  $st->bind_param("i", $cid);
}
$st->execute();
$res = $st->get_result();
while($row = $res->fetch_assoc()) {
  $items[] = $row;
}
$i = 0;
for($r = 0; $items[$i] && $r < 5; $r++) {
  echo "<tr>";
  for($c = 0; $items[$i] && $c < 2; $c++) {
    if ($c) echo "<td style='width:50px;'>";
    echo "<td>";
    show($items[$i++]);
  }
}

?>
</table>
</table>
</body>
</html>