如何在php中通过id调用rest api? [关闭]

问题描述 投票:-5回答:1

现在我可以输出http://localhost/posts/

[
  {
    "id": "1",
    "title": "first post",
    "description": "here my first post",
    "status": "Y"
  },
  {
    "id": "2",
    "title": "second post",
    "description": "here my second post",
    "status": "Y"
  }
]

这是我的源代码

if ($_SERVER['REQUEST_METHOD'] == "GET"){
    @List($objnm, $objid) = explode('/', $_GET['url']);
    if ($objnm == 'posts')
    {
        $post = $db->query('SELECT * FROM post WHERE status="Y"');
        echo json_encode($post, JSON_PRETTY_PRINT);
    }
    else
    {
        http_response_code(401);
    }

}

我的htaccess

RewriteEngine On
RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA]

我需要输出http://localhost/posts/1任何人都可以帮助我吗?

php rest
1个回答
1
投票

我将建议使用is_numeric()函数来检查第二个参数是否为数字。

if ($_SERVER['REQUEST_METHOD'] == "GET"){
    @List($objnm, $objid) = explode('/', $_GET['url']);
    if ($objnm == 'posts')
    {
        if(is_numeric($objid)) {
            $post = $db->query('SELECT * FROM post WHERE status="Y" AND id="'.$objid.'";');
            echo json_encode($post, JSON_PRETTY_PRINT);
        }
        else 
        {
            $post = $db->query('SELECT * FROM post WHERE status="Y"');
            echo json_encode($post, JSON_PRETTY_PRINT);
        }
    }
    else
    {
        http_response_code(401);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.