Search code examples
phpmysqlsqlurllithium

Going from, SELECT * FROM users WHERE url = "pretty url", to displaying 1 row from database with Lithium Framework


Hi I am new to php and mysql and jumped right into using the Lithium framework.....I know, bad idea.

BUT basically my question is, how do I go from;

$users = \app\models\Users::findByUrl($this->request->query['url']);
return array(
  'users' => $users,
 );

in my UsersController to actually echo'ing 1 specific row of data in my users/index.php.html page, according to the query string in my url?

My desired structure is localhost/users/"url", and "url" is a value in my mysql db labeled "url" in my Users table. e.g. localhost/users/Bob. "Bob" is "url" value.

My users/index.php.html page is using foreach ($users as $user) to echo the information like this;

<?=$user->firstname ?>

Snag and Confusion:

When I was using;

$users = \app\models\Users::find('all');
return array(
 'users' => $users,
);

in my UsersController, the users/index.php.html page retrieved all the users in my database.

The content displays correctly, BUT I need the data from just the clicked-on user, so this is when I started using; $users = \app\models\Users::findByUrl($this->request->query['url']);

When linking to the users page this is how I do it;

<?php if( $user->avatar ):?> 
 <a href="/users/<?=$user->url?>">
      <img class="img-responsive" src="/img/users/<?=$user->avatar?>" />  
 </a> 
<?php else: ?>

Not sure if I need to add conditions to my controller, add something to my router, change my htaccess, or do something with params.... Pleease help, any direction would be greatly appreciated.


Solution

  • Finders return everything by default. If you want a single object, do:

    Users::findFirstByUrl($this->request->query['url'])

    ...which is short-hand for:

    Users::first(['conditions' => ['url' => $this->request->query['url']]]) or Users::find('first', ['conditions' => ['url' => $this->request->query['url']]]).