CRUD on people

master
Matt Huntington 7 years ago
commit 09477690f4

@ -0,0 +1,10 @@
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^GET$
RewriteRule ^people$ controllers/people.php?action=index
RewriteCond %{REQUEST_METHOD} ^POST$
RewriteRule ^people$ controllers/people.php?action=post
RewriteCond %{REQUEST_METHOD} ^PUT$
RewriteRule ^people/([0-9]+)$ controllers/people.php?action=update&id=$1
RewriteCond %{REQUEST_METHOD} ^DELETE$
RewriteRule ^people/([0-9]+)$ controllers/people.php?action=delete&id=$1

@ -0,0 +1,27 @@
<?php
header('Content-Type: application/json');
include_once __DIR__ . '/../models/person.php';
if($_REQUEST['action'] === 'index'){
echo json_encode(People::all());
} else if ($_REQUEST['action'] === 'post'){
$request_body = file_get_contents('php://input');
$body_object = json_decode($request_body);
$newPerson = new Person(null, $body_object->name, $body_object->age);
$allPeople = People::create($newPerson); //store the return value of People::create into a var
//send the return value of People::create (all people in the db) back to the user
echo json_encode($allPeople);
} else if ($_REQUEST['action'] === 'update'){
$request_body = file_get_contents('php://input');
$body_object = json_decode($request_body);
$updatedPerson = new Person($_REQUEST['id'], $body_object->name, $body_object->age);
$allPeople = People::update($updatedPerson);
echo json_encode($allPeople);
} else if ($_REQUEST['action'] === 'delete'){
$allPeople = People::delete($_REQUEST['id']);
echo json_encode($allPeople);
}
?>

@ -0,0 +1,58 @@
<?php
$dbconn = pg_connect("host=localhost dbname=contacts2");
class Person {
public $id;
public $name;
public $age;
public function __construct($id, $name, $age) {
$this->id = $id;
$this->name = $name;
$this->age = $age;
}
}
class People {
static function create($person){
$query = "INSERT INTO people (name, age) VALUES ($1, $2)";
$query_params = array($person->name, $person->age);
pg_query_params($query, $query_params);
return self::all(); //find all people and return them
}
static function delete($id){
$query = "DELETE FROM people WHERE id = $1";
$query_params = array($id);
$result = pg_query_params($query, $query_params);
return self::all();
}
static function update($updatedPerson){
$query = "UPDATE people SET name = $1, age = $2 WHERE id = $3";
$query_params = array($updatedPerson->name, $updatedPerson->age, $updatedPerson->id);
$result = pg_query_params($query, $query_params);
return self::all();
}
static function all(){
//create an empty array
$people = array();
//query the database
$results = pg_query("SELECT * FROM people");
$row_object = pg_fetch_object($results);
while($row_object){
$new_person = new Person(
intval($row_object->id),
$row_object->name,
intval($row_object->age)
);
$people[] = $new_person; //push new person object onto $people array
$row_object = pg_fetch_object($results);
}
return $people;
}
}
?>
Loading…
Cancel
Save