kmancusi kmancusi - 7 months ago 12
PHP Question

PHP and basic RESTful services; GET requesting all records vs one record

My PHP class has a project involving RESTful services where we have a basic service set up like this:


$request = $_SERVER["REQUEST_METHOD"];
switch($request) {
case 'GET':
$user = $acctReader->read($_GET["username"], $_GET["password"]);
if (isset($_GET["id"]) && $user == true) {
// echo method to return single record from db after validating that $user is an account in a separate table
} elseif (!isset($_GET["id"] && $user == true) {
// echo method to return ALL records from db
}
case 'POST':
case 'PUT':
case 'DELETE':
default
}


I'm in the midst of having the GET to respond to user validation in such that if they enter in a valid username/password but do not explicitly request a single id, they should see all the records

Here's what part of my html looks like:

<form action="TaskService.php" method="GET">
<label for="username">Username</label>
<input type="text" name="username" id="username" required/><br />
<label for="password">Password</label>
<input type="password" name="password" id="password" required/><br />
<label for="id">Task ID</label>
<input type="text" name="id" id="id" placeholder="optional"/>
<input type="submit" name="getTask" value="GET TASK"/>
</form>


I was able to verify that my first conditional (where the username, pw, and an id are entered) that it returns one value. However, I am having trouble with having it give me all records when I don't pass an id in.
Any ideas on where I should be making my changes?

Answer

The $_GET["id"] will be SET even if it is empty. You will have to either us

if (!empty($_GET["id"]) && $user == true) {
    // echo method to return single record from db after validating that $user is an account in a separate table
} else {
    // echo method to return ALL records from db
}

Or

if (isset($_GET["id"]) && $_GET["id"] != '' && $user == true) {
    // echo method to return single record from db after validating that $user is an account in a separate table
} else {
    // echo method to return ALL records from db
}