commit 09477690f47d5490299079780f80c34a40f33eb1 Author: Matt Huntington Date: Sat Jan 26 16:05:47 2019 -0500 CRUD on people diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..ae1ce6e --- /dev/null +++ b/.htaccess @@ -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 diff --git a/controllers/people.php b/controllers/people.php new file mode 100644 index 0000000..c1eadc5 --- /dev/null +++ b/controllers/people.php @@ -0,0 +1,27 @@ +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); +} + +?> diff --git a/models/person.php b/models/person.php new file mode 100644 index 0000000..40d00a3 --- /dev/null +++ b/models/person.php @@ -0,0 +1,58 @@ +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; + } +} +?>