Passing Database Array As A String

I need to search for the primary key value from a database table by using a value from another column and pass the primary key in the loadModel argument. The code I used in the loadModel method is shown below,

	$sql = "SELECT itemNo FROM inv_item WHERE medcineId =$id";


	$connection=Yii::app()->db;


	$command=$connection->createCommand($sql);


	$orderList=$command->queryAll();


	$model=Item::model()->$orderList[0];


	if($model===null)


		//throw new CHttpException(404,'The requested page does not exist.');


	return $model;

The problem is, that when I run this page it displays undefined offset error message

Any ideas on how this could be fixed

there are several problems here:




$model=Item::model()->$orderList[0];



it does not make much sense unless there is attribute in model with name equal to "itemNo" value… if this is a foreign key you should rather use:




$model=Item::model()->findByPk($orderList[0]);



also look at this part:




if($model===null)

//throw new CHttpException(404,'The requested page does not exist.');

return $model;



it means that $model will be returned only when it is null, because "throw" line is commented. Otherwise nothing is returned.

This is why I am always putting {} braces after if/for/while etc, and thing I do not like in Yii code…

Anyway - If above does not solve your problem, check your logs (in protected/runtime directory) and see the callstack where exactly is the error thrown and paste it here.

Previously it mentioned array to string conversion, however after I used the code you gave it says Undefined offset

I have attached the stack trace here. I renamed it to .txt because .log files are not permitted to be uploaded here

well - it says: Undefined offset: 0

this means there is no element with offset 0 in array: $orderList[0]

try to output its content to check if it is empty or has some other keys:




print_r( $orderList );

exit;



you should also check if the previous query returns anything…

I tried using the print statement but it only displays the error message even after I refresh the page.

print_r is for debugging. put it just after




$orderList=$command->queryAll();

print_r( $orderList );

exit;



now you are getting same error as earlier which means "findByPk" was called:

2013/01/31 10:33:55 [error] [php] Undefined offset: 0 (C:\Users\dell\Dropbox\www\yii\framework\db\schema\CDbCommandBuilder.php:663)

Stack trace:

#0 C:\Users\dell\Dropbox\www\ayur_mis\protected\controllers\ItemController.php(188): Item->findByPk()

#1 C:\Users\dell\Dropbox\www\ayur_mis\protected\controllers\ItemController.php(55): ItemController->loadModel()

#2 unknown(0): ItemController->actionView()