} upon successful update * - { "error" : } if an error occurs (see below) * * Invalid Request (400) Errors (in order of precedence): * - Missing required name POST parameter * - Missing one of price or cost POST parameters * - A price or cost is passed as a negative value * * Service Unavailable (503) Error when a DB connection occurs */ include("common.php"); if (isset($_POST["name"])) { $name = $_POST["name"]; $price = NULL; $cost = NULL; if (isset($_POST["price"])) { $price = round(floatval($_POST["price"]), 2); check_negative($price); # will die/terminate with 400 error if negative } if (isset($_POST["cost"])) { $cost = round(floatval($_POST["cost"]), 2); check_negative($cost); } if ($price !== NULL || $cost !== NULL) { update_item($name, $price, $cost); } else { # Missing one required price/cost to update handle_request_error("Missing price or cost parameter."); } } else { # Missing required name parameter handle_request_error("Missing required name parameters."); } /** * Updates the menu with the given $name and $price/$cost. * Outputs a JSON response with a success message upon successful update, otherwise a * descriptive error message (see web service documentation for possible errors). * * @param $name {string} - name of item to update * @param $price {number|NULL} - price of item to update if not NULL. * @param $cost {number|NULL} - cost of item to update if not NULL. */ function update_item($name, $price, $cost) { $db = get_PDO(); $item_data = find_item($db, $name); if (!$item_data) { # no item data was found in find_item call, terminate with JSON error message handle_request_error("{$name} not found on the menu!"); } # else, update the menu! if ($price === NULL) { $price = $item_data["price"]; } if ($cost === NULL) { $cost = $item_data["cost"]; } # alternatively, you could have a different UPDATE statement depending on # whether price, cost, or both were passed to update. $qry = "UPDATE menu SET name=:name, price=:price, cost=:cost WHERE name=:name"; try { $stmt = $db->prepare($qry); $params = array("name" => $name, "price" => $price, 2, "cost" => $cost); $stmt->execute($params); } catch (PDOException $ex) { handle_db_error(); } # If you want to format a number with 2 decimal places, remember you can use number_format(, 2)! $formatted_cost = number_format($cost, 2); $formatted_price = number_format($price, 2); output_success("{$name} now has a cost of \${$formatted_cost} and price of \${$formatted_price}!"); } ?>