0

I use create command of Yii as

$sql = "select name from users where id = 2";

$EmployeeName=Yii::app()->db->createCommand($sql)->queryAll();

now i have to use foreachloop to get specific value like

foreach($EmployeeName as $value)
$name = $value['name'];

Can i bypass foreach loop like

$EmployeeName -> name; //To get value of specific field 

Question is why i use foreach loop when i know i have single index array? when i am using print_r($EmployeeName) its showing me sql command in object instead of data so i am confused how to debug object array

1
  • I think its because you are using query all. try $EmployeeName[0]->name Commented Dec 4, 2014 at 7:04

3 Answers 3

1

Assuming id is your primary key, you should use queryScalar instead. This will return a single value and not an array.

$name=Yii::app()->db->createCommand($sql)->queryScalar();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this syntax in Yii:

$user = Users::model()->findByAttributes(array('id' => 2));
$name = $user->name;
echo $name;

Comments

0

Single line solution

The simplest approach is find by primary key (PK).

Suppose id is PK in the Users model (Users model should be set thru gii model generator):

$name = Users::model()->findByPk(2)->name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.