I've been trying to get the results from my query for the past two hours, in my model I have this
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
in the controller
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$model=new QuoteForm();
if(isset($_POST['QuoteForm']))
{
$model->attributes=$_POST['QuoteForm'];
if ($model->validate())
{
$priceTable=new CityFareFinal;
$priceTable->fromm=$model->pickupL;
$priceTable->too=$model->dropoffL;
$priceTable->type_of_car=$model->type;
this->render('result',array('model'=>$priceTable))
}
}
else
{
$this->render('index',array('model'=>$model));
}
}
and in the view
<div id="moduleResult">
<span><?php echo $model->getQuotes() ;?><------ Here</span>
</div>
but it always give me an error saying "Object of class CDbCommand could not be converted to string ", what can I do to get the results of my query made in the model???
Regards Gabriel
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
Your getQuotes() return Object of class CDbCommand
:
+ You returned $data in the function instead of $data->queryRow().
By the way, you cannot use echo
for array
data.
The below example is used for fetching data from DB to view by using DAO with Yii: I suppose you have Person model and Person controller
In your Person model:
function getData() {
$sql = "SELECT * from Person";
$data = Yii::app()->db
->createCommand($sql)
->queryAll();
return $data;
}
In your controller:
function index(){
$data = Person::model()->getData();
$this->render('your_view',array(
'data'=>$data,
));
}
In your view: you can foreach
your data to echo items in the array
data:
<?php foreach($data as $row): ?>
//show something you want
<?php echo $row->name; ?>
<?php endforeach; ?>
$data->queryRow();
returns result in array format. Your code is returning $data
which is an object not result of query. That's why you are getting this error.
If you want to fetch single value you can use $data->queryScalar();
In case of queryRow()
your code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select * from city_fare_final');
$result = $data->queryRow();
return $result ; //this will return result in array format (single row)
}
for a single field value you code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select xyz from city_fare_final');
$result = $data->queryScalar();
return $result; //return single value of xyz column
}
I hope this will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With