We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to query something from database depending on the URL param?

Hello guys,

i got an news article system where users can click on "read more" The url is: localhost/articles/{id} where {id} is, is the ID from the article which is outputted from the database.

Now what i want to do is, whenever the user clicks on read more, i need to get the database info for the article name, title , text etc depending on the URL id param.

Anyone can help me?

Thank you.

This is my router:

$router->add( '/articles/index/{id}', [ 'controller' => 'Articles', 'action' => 'index', ] );



145.0k
Accepted
answer
public function indexAction($id)
{
    $whatever = $whateverModel::findFirst($id;
}


460

This works, but the findFirst gets the first ID from the database, i want the ID from the current article which is clicked (as shown in the URL))

index.php?articleid=26

This should get article info where ID is 26.

public function indexAction($id)
{
   $whatever = $whateverModel::findFirst($id;
}
edited Jun '18

???? Then access url how you provided in route like:

/articles/index/26

26 will be passed to indexAction as $id



2.9k

And don't forget to sanitize the input. ;)

In case your URIs look like the route you've set (/articles/index/{id}):

  public function indexAction($articleId) {
         $articleId = $this->filter->sanitize($articleId, 'int');
         $Article = Articles::findFirstById($articleId);
      }

In case a GET variable holds the article ID (/articles/index?articleid={id}):

  public function indexAction() {
         $articleId = $this->request->getQuery('articleid', 'int');
         $Article = Articles::findFirstById($articleId);
      }
edited Jun '18

Well it's better to put {id:int} in route.



2.9k
edited Jun '18

Well it's better to put {id:int} in route.

I don't use manual routes in my applications, so I didn't think of that. I suppose that could be a solution in some cases, although, whether we use {id:int} or not, I would still keep the extra sanitization within the action.

edited Jun '18

If you use {id:int} then action will be only executed if int is passed, then you are certain that you have int there - not reason to sanitize.



2.9k

I understand that, but if someone updates the routes in a less-than-optimal fashion in the future, and there is no sanitization within the action, undesired consequences could follow. We've actually had kind of a similar accident. So my stance on this is that the extra sinitization is worth it. Better safe than sorry. :)

Yea i agree, but still i prefer not to do same thing two times.