query("SELECT name, price FROM Inventory"); header("Content-type: text/plain"); foreach ($rows as $row) { $price = number_format($row['price'], 2); echo "{$row['name']} ({$price})\n"; } } catch (PDOException $ex) { handle_error("Cannot query from database", $ex); } } */ # Exercise 2 Part I (JSON) function get_item_prices($db) { # select all rows from the Inventory table try { # Note that we use query here instead of prepare/exec because we don't use any # variables which a user has access to (recall we want to use prepare/exec to # prevent SQL injection from user input) $rows = $db->query("SELECT name, price FROM Inventory;"); $output = array(); foreach($rows as $row) { $item_data = array(); $item_data["name"] = $row["name"]; $item_data["price"] = doubleval($row["price"]); array_push($output, $item_data); } #encode the output array as json header("Content-Type: application/json"); print(json_encode($output)); } catch (PDOException $ex) { handle_error("Cannot query the database", $ex); } } # Exercise 2 Filtered Query function get_category_data($db, $category) { try { $qry = "SELECT name, category, subcategory, price, cost, description FROM Inventory WHERE category=:category;"; # In this part, we _do_ want to use prepare/execute to execute the SQL query instead of # $db->query. This is because we want to ensure the input is "sanitized" before # executing the query on the database ($db->query will always execute the query, which # can be dangerous if the user passes strings with DROP TABLE, etc.!). $stmt = $db->prepare($qry); $params = array("category" => $category); $stmt->execute($params); $rows = $stmt->fetchAll(); $data = get_item_data($db, $rows); if (count($data) >= 0) { header("Content-Type: application/json"); print(json_encode($data)); } else { handle_error("Category {$category} not found in our inventory."); } } catch (PDOException $ex) { handle_error("Internal database error", $ex); } } # Helper function function get_item_data($db, $rows) { $output = array(); foreach($rows as $row) { $item_data = array(); $item_data["name"] = $row["name"]; $item_data["category"] = $row["category"]; $item_data["subcategory"] = $row["subcategory"]; $item_data["price"] = doubleval($row["price"]); $item_data["cost"] = doubleval($row["cost"]); $desc = $row["description"]; if ($desc) { $item_data["description"] = $desc; } array_push($output, $item_data); } return $output; } ?>