-5

now i can output 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"
  }
]

here my source code

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);
    }

}

my htaccess

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

i need output for http://localhost/posts/1 any one can help me?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    Possible duplicate of [.htaccess rewrite "/book.php?id=1234" to "/book/1234"](https://stackoverflow.com/questions/11696718/htaccess-rewrite-book-phpid-1234-to-book-1234) – sumit Dec 13 '17 at 20:50

1 Answers1

1

I will suggest the is_numeric() function to check if the second parameter is a number.

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);
    }

}