Skip to content

Instantly share code, notes, and snippets.

@harshadura
Created July 3, 2012 17:04
Show Gist options
  • Save harshadura/3041075 to your computer and use it in GitHub Desktop.
Save harshadura/3041075 to your computer and use it in GitHub Desktop.
Ralapanawa REST web service demo
<?php
function getStatusCodeMessage($status)
{
$codes = Array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
return (isset($codes[$status])) ? $codes[$status] : '';
}
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
class RalapanawaAPI {
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'root', 'sa', 'ralapanawa');
}
function __destruct() {
$this->db->close();
}
function rala() {
if (isset($_POST["tank_id"]) && isset($_POST["water_level"]) ) {
try{
$tank_id = $_POST["tank_id"];
$water_level = $_POST["water_level"];
$stmt = $this->db->prepare("INSERT INTO water_level (tankid, Depth) VALUES (?, ?)");
$stmt->bind_param("ss", $tank_id, $water_level);
$stmt->execute();
$stmt->close();
sendResponse(200, 'Water Level Saved!');
return true;
} catch (Exception $e) {
$err = 'Caught exception: '. $e->getMessage(). "\n";
sendResponse(200, $err);
return false;
}
}
if (isset($_POST["tank_id"]) ) {
$depth = "";
$tank_id = $_POST["tank_id"];
$stmt = $this->db->prepare("SELECT Depth FROM water_level WHERE tankid=?");
$stmt->bind_param("s", $tank_id);
$stmt->execute();
$stmt->bind_result($depth);
while ($stmt->fetch()) {
break;
}
$stmt->close();
$result = array(
"water_level" => $depth
);
sendResponse(200, json_encode($result));
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
}
$api = new RalapanawaAPI;
$api->rala();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment