PHP and basic RESTful services; GET requesting all

2019-08-30 22:44发布

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?

标签: php rest get
1条回答
相关推荐>>
2楼-- · 2019-08-30 22:54

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
}

But beware of using empty() when the field could contains

  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)

as these are all considered as empty

See the manual

查看更多
登录 后发表回答