【问题标题】:how to call rest api by id in php? [closed]如何在php中通过id调用rest api? [关闭]
【发布时间】:2017-12-13 20:45:53
【问题描述】:

现在我可以输出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】:

我会建议使用 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);
    }

}

【讨论】:

  • 我已经更改了我的源代码。现在我已经改变了我的 htaccess 不起作用。
  • 可以查看 RewriteRule (.*)$ index.php?url=$1 [QSA,L]
  • 非常感谢兄弟。现在运行;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2017-12-05
相关资源
最近更新 更多