Dave
Dave

Reputation: 205

How to return a specific output to a variable using raw query in cakephp

I have a variable which needed a value from a specific query

$player_id_owner = $this->Player->fetchAll('Select id from player where name = ?', array($name));

 $player_id_owner = ($this->Player->find('all', array(
                    'fields' => array('id'),
                    'conditions' => array('Player.name' => '$name')
                    )));

i tried both raw query and cakephp find but both of them returns only "array"

have i forgotten something? how can i access the expected result from query? thanks

Upvotes: 0

Views: 437

Answers (2)

p0d4r14n
p0d4r14n

Reputation: 681

try this

 $player_id_owner = $this->Player->find('first', array(
                      'fields' => array('id'),
                      'conditions' => array('Player.name' => $name)
                    ));

or try (you can also use your variable instead of yourname)

'conditions' => array('Player.name LIKE' => "%yourname%")

after that you can get the id with

$player_id_owner['Player']['id']

Upvotes: 0

mark
mark

Reputation: 21743

Well

'Player.name' => '$name'

is not valid PHP code, at least not for what you try to do. Don't escape variables as strings:

'Player.name' => $name

You could have easily seen that by checking the resulting query in the debug kit or the bottom of the view.

And most likely you would want to use find('first', ...) as documented if you only expect a single entry here.

Last but not least: You most likely just lack basic debugging skills. Don't echo it, as it is indeed an array. Never do that with unknown variables as they often are everything but a basic string. Use debug() to see whats inside and then properly echo what you see, e.g. echo $player['Player']['name'];.

Bear in mind that stringish output should be secured by h() on output:

echo h($player['Player']['name']);

Upvotes: 0

Related Questions