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.
below sample code to traverse rows returned by queryAll
$connection = Yii::app()->db;
$command = $connection->createCommand("Select * from table");
$caterow = $command->queryAll(); //executes the SQL statement and returns the all rows
foreach($caterow as $retcat )
{
echo $retcat["ColumnName"] ;
}
Returns Arrary of rows with fields
Model: Notices.php:
---------------------------------
public function getNoticesBlog($offset = 0){
$dataResult = Yii::app()->db->createCommand()->select('*')->from($this->tableName())
->andWhere("delete_flg=:delete_flg",array(':delete_flg'=>0))
->andWhere("publish=:publish",array(':publish'=>1))
->limit(3)->offset($offset)->order('created_on DESC')->queryAll();
return $dataResult;
}
Controller: NoticesController.php
$firstNotices = Notices::model()->getNoticesBlog(0);
$secondNotices = Notices::model()->getNoticesBlog(3);
$thirdNotices = Notices::model()->getNoticesBlog(6);
$this->render('Notices',array(
'firstNotices'=>$firstNotices,
'secondNotices'=>$secondNotices,
'thirdNotices'=>$thirdNotices,
)
);
Related
I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code
Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$data);
}
1) to fetch the entire data from a table in codeigniter
Model Code
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->result();
}
View Code
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
2) to fetch number of rows from a table in codeigniter
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->num_rows();
}
View Code
echo $instant_req;
You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records
for example in the model
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$result=$query->result();
$num_rows=$query->num_rows();
$last_three_record=array_slice($result,-3,3,true);
return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}
in controller dashboard function
public function dashboard()
{
$result = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$result);
}
in view
foreach ($all_data as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//latest three record
foreach ($last_three as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//total count
echo $num_rows;
Raw query may work here.
$resultSet = $this->db->query("select * from table_name");
$queryCount = count($resultSet );
Try this logic :
Model code :
public function getreq()
{
$this->db->where('status','pending');
$this->db->order_by('id', 'DESC'); //actual field name of id
$query=$this->db->get('instanthire');
return $query->result();
}
Controller Code :
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$data['total_record'] = count($data['instant_req']);
$this->load->view('admin/dashboard',$data);
}
View Code:
$i=0;
foreach ($instant_req as $perreq)
{
if($i<3){
echo $perreq->fullname;
echo "<br>";
}
$i++;
}
Echo 'Total record : '.$total_record;
Function
function getData($limit = 0){
//Create empty array
$data = [];
//Where clause
$this->db->where('status','pending');
//Order Data based on latest ID
$this->db->order_by('id', 'DESC');
if($limit != 0){
$this->db->limit($limit);
}
//Get the Data
$query = $this->db->get('instanthire');
$data['count'] = $query->num_rows();
$data['result'] = $query->result();
return $data;
}
Calls
//Last 3 Inserted
$data = getData(3);
//All Data
$data = getData();
CodeIgniter Database Documentation
Here is a simple solution that I can first think of but if you want me to maybe improve I can.
Just stick with your first code(Model) and in the view count how many items are iterated through.
$count = 0;
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
$count++;
}
echo $count;
Am I still missing something? just let me know
EDIT:
This is another solution, return an array
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$data['results'] = $query->result();
$data['count'] = $query->num_rows();
return $data
}
I'm not very confident and haven't really tried this but on top of my head I think it can work.
Model:
public function getreq()
{
$res = $this->db->order_by("<place column primary id>","desc")->get_where('instanthire',['status'=> 'pending']);
$latest_3 = [];
if(count($res)){
$i=1;
foreach($res as $r){
$latest_3[]=$r;
if($i == 3)
break;
$i++;
}
}
$arr = [
'latest_3' => $latest_3,
'count' => count($res),
'total_result' => $res,
];
return $arr;
}
This is code query data from database :
public function getAllUser(){
$connect = Yii::app()->db;
$query = "SELECT * FROM user";
$statement = $connect->CreateCommand($query);
$result = $statement->query();
return $result;
}
After that I use Controller to get data & send to View :
public function actionIndex()
{
$consultas = new ConsultasDB();
$listUser = $consultas->getAllUser();
$this->render('index', array
("listUser" => $listUser));
}
In View I know show all information from database by loop listUser
foreach ($listUser->readAll() as $user)
{
echo 'Username : '.$user["username"].'<br>';
echo 'Password : '.$user["password"].'<br>';
}
but I don't know how to get a object with an index. Ex: User[1]...
Thanks!
Add this in your view, before the foreach loop
echo "<pre>";
print_r($listUser->readAll());
echo "</pre>";
Hope this helps you out.!
I'm working on a project. how to calculate comment by id?
example
controler:
public function comments() {
$id_alat = $this->db->where('id_alat');
$com = $this->mcrud->getComent($id_alat);
$com = $this->mcrud->getComent($id_alat);
$data = array (
'com' => $com,
'content' => 'instrument/instrument');
$this->load->view('layouts/wrapper', $data);
}
models:
public function getComent($id_alat) {
$sql = "SELECT count (*) as num FROM WHERE tbcoment $id_alat tbcoment.id_alat = {}";
$this->db->query($sql);
}
view:
comments: <?php echo $com; ?>
Use following code for model
Your Model
public function getComent($id_alat)
{
$sql = "SELECT count (*) as num FROM WHERE tbcoment.id_alat = '$id_alat'";
$res=$this->db->query($sql)->row_object();
return $res->num;
}
Note: Don't use spaces inside php tags and variables.
Ex01: $ id_alat should come $id_alat
Ex02: $ this-> mcrud-> getComent ($ id_alat); should come $this->mcrud-> getComent($id_alat);
Code Example
In controller
function comments () {
$id_alat = '';//Asign data to here
$data['com'] = $this->Model_name->getComent($id_alat);
$data['content'] = 'instrument / instrument';
$this->load->view ('layouts/wrapper', $data);
}
In Model
function getComent($id_alat) {
$query =$this->db->query("SELECT * FROM table_name WHERE tbcoment='$id_alat'");//cahnge table name, and argument that you want
$result = $query->result_array();
$count = count($result);
return $count;
}
In view
comments: <?php echo $com; ?>
you can also use this code:
$this->db->where('id',$id)
->from('table_name')
->count_all_results();
this can be used either on MVC(Model, View, Controller);
you can find this code on the user guide
I am newbie in codeigniter. If I have a model like this :
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row();
}
And I try to accessed it from may controller :
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
How to Generating Query Results, thanks for the help.
EDIT
I am new in CI, my question is : let's say I want to get the 'nama_user' into an a variable like this :
foreach ($data as $d) {
$name = $d['nama_user'];
}
echo json_encode($name);
I use firebug, it gives me null. I think my foreach is in a problem
In order to return an array from your model call you can use result_array() as
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->result_array();//<---- This'll always return you set of an array
}
Controller File with your query code
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
//Generating Query Results like this because you use $query->row();
$data->nama_user;
$data->keluhan;
$data->email;
$data->addresed_to;
$info_json = array("nama_user" => $data->nama_user, "keluhan" => $data->keluhan, "email" => $data->email, "addresed_to" => $data->addresed_to);
echo json_encode($info_json);
}
MODEL.PHP
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row_array();
}
//Generating Query Results if use $query->row_array(); in model file
Controller.php
function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
foreach($data as $row)
{
$myArray[] = $row;
}
echo json_encode($myArray);
You fetched data for selected id it means you get a single row, if you want to get "nama_user" then in your controller:
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
$name = $data->nama_user;
echo json_encode($name);
}
I am writing a form, which has a select menu in it, I want the values to pulled from the database, so I thought it would be something along these lines:
My view
<?php
echo form_open('admin/save_content');
echo form_fieldset();
echo form_dropdown('categories', $select_options);
echo form_submit('category_submit', 'Submit');
echo form_fieldset_close();
echo form_close();
?>
My controller
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$data['select_options'] = $this->category_model->get_all_online();
$this->load->view('admin/content/add_content', $data);
}
my model
public function get_all_online() {
$this->db->select('*');
$this->db->from('category');
$this->db->where('category_online', 1);
$query = $this->db->get();
return $query->result();
}
now when I place the $selected_options in the form dropdown I get this error,
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass
could not be converted to string
Filename: helpers/form_helper.php
Line Number: 331
You need to pass an array to your dropdown, where the array key will be the value that is POSTed and the value will the text that is displayed.
To achieve this, change your controller like so:
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$data['select_options'] = $this->category_model->get_all_online_select();
$this->load->view('admin/content/add_content', $data);
}
and add this function to your model
public function get_all_online_select() {
$this->db->select('id, name'); //change this to the two main values you want to use
$this->db->from('category');
$this->db->where('category_online', 1);
$query = $this->db->get();
foreach($query->result_array() as $row){
$data[$row['id']]=$row['name'];
}
return $data;
}
That should do the trick
I personally hate to make assumptions in my Models about how my data will be used as that is the job of the controller. If you add a MY_array_helper.php and paste this in:
function array_to_select() {
$args = func_get_args();
$return = array();
switch(count($args)):
case 3:
foreach ($args[0] as $itteration):
if(is_object($itteration)) $itteration = (array) $itteration;
$return[$itteration[$args[1]]] = $itteration[$args[2]];
endforeach;
break;
case 2:
foreach ($args[0] as $key => $itteration):
if(is_object($itteration)) $itteration = (array) $itteration;
$return[$key] = $itteration[$args[1]];
endforeach;
break;
case 1:
foreach ($args[0] as $itteration):
$return[$itteration] = $itteration;
endforeach;
break;
default:
return FALSE;
break;
endswitch;
return $return;
}
Then you can do something like this:
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$this->load->helper('array');
$data['select_options'] = array_to_select($this->category_model->get_all_online(), 'id', 'title');
$this->load->view('admin/content/add_content', $data);
}
That supports multi-dimensional arrays by passing in one or two keys, or single dimensional arrays by using the value as the value and the key.
Eg: array_to_select(array('value1', 'value2')) gives array('value1'=>'value1', 'value2'=>'value2')
You need to return an array of strings, result() is an array of objects.
Maybe try this in your model:
return $query->result_array();
In your view, you can add foreach there instead of in Model.
<?php
echo form_open('admin/save_content');
echo form_fieldset();
foreach($select_options->result_array() as $row){
$data[$row['id']]=$row['name'];
echo form_dropdown('categories', $row);
}
echo form_submit('category_submit', 'Submit');
echo form_fieldset_close();
echo form_close();
?>
Not tested.
I have edited Phil Surgeon's array helper to work with a simple db query with only two fields (id & value). So the helper class now looks like this:
<?php
function array_to_select() {
//get args
$args = func_get_args();
//get args key names
$keys = array_keys($args[0][0]);
//set return array
$return = array();
foreach ($args[0] as $itteration){
//$itteration[$keys[0]] is field id value, $itteration[$keys[1]] is field name value
$return[$itteration[$keys[0]]] = $itteration[$keys[1]];
}
return $return;
}
And you can use it again in your controller.
Hope it's usefull.
form drop down with lot of options codeigniter form drop down menu with validation class also