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);
}
Related
I have an error in my controller. I am trying to use the result coming from model function to call another function in my model. I am using Codeigniter Framework. hope you can help me out. Thanks
Controller:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
My Model:
function get_all_photographer_campaign_details($camp_id) {
$this->db->select('*');
$this->db->where('campaign_id',$camp_id);
$query = $this->db->get('ps_campaigns');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
return $data;
}
return array();
}
//get seller name by id
function get_seller_name_by_id($uid)
{
$this->db->select('firstname, lastname');
$this->db->where('id', $uid);
$query = $this->db->get('ps_users');
//return $query->row();
return $query->result_array();
}
an error is coming from the controller: Undefined index: uid
Looking at your get_all_photographer_campaign_details, if no rows are found then you return an empty array.
In your controller, you never check to see if a valid entry was found. As a result you get your undefined index: uid when an id is referenced in the URL that doesn't correspond to an entry, because $campaign is empty and doesn't have a uid key. Try something like this:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
if (!$campaign ){
show_404();
}
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
Additionally, you are returning data wrong in the event that you do find data. Namely this bit in get_all_photographer_campaign_details:
foreach ($query->result_array() as $row) {
$data[] = $row;
}
Should be something like:
foreach ($query->result_array() as $row) {
$data = $row;
break;
}
The problem is that you are appending the row as one row in $data, but your controller is expecting to get the actual data itself. I.e. your controller is expecting this:
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
But you are returning this:
[
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
]
Note the extra array that everything is wrapped around. Basically, your model is returning an array of results, when your controller is just expecting results. My above suggestion will work if there is only ever supposed to be one campaign returned. If that is not the case, then you need to adjust your controller instead of your model method.
To reiterate my other point: make sure and validate the user input that comes from the URL. Otherwise you will return PHP errors instead of 404's.
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;
}
Let's assume I have this controller function
public function index(){
$this->load->model('model_users');
$clienteemail = $this->session->userdata('email');
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
$data['title']='La Giumenta Bardata Dashboard'; //array per titolo e dati passati
$this->load->view('auth/template/auth_header', $data);
$this->load->view('auth/template/auth_nav', $cliente);
$this->load->view('auth/clienti/auth_sidebar');
$this->load->view('auth/clienti/client_dash');
$this->load->view('auth/template/auth_footer');
}
model_users is a model that query the db with this function:
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query) {
$row = $query->row();
$cliente['nome'] = $row->nome;
return $cliente;
} else {
echo "errore nella ricerca del nome";
}
What I'm trying to do is to use an user email from the session data to retrieve info from the db table.
so I start to retrieve just the name of the user.
The function works, but when in the view I use echo $nome;
I have an error about the conversion between array and string... that's normal, I know, but if I do
print_r($nome);
my output is: Array[0] => 'Pippo'
I just want to output the content of the array.
How can I achieve this?
It looks like you've made a bit of a typo..
Your model:
$row = $query->row(); // Fetch the entireuser
$cliente['nome'] = $row->nome; // Set the name to a value. $cliente isn't defined yet..
return $cliente; // Return the entire $cliente array.
Your Controller:
You are using the above model method and assuming it is returning just the name. It is actually returning the full user.
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
Change your model code to the following and it should work as expected.
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query && $query->num_rows() > 0) { // Ensure we have got at least 1 row
$row = $query->row();
return $row->nome;
} else {
echo "errore nella ricerca del nome";
}
}
return $row->nome;
instead of:
$cliente['nome'] = $row->nome;
return $cliente;
OR
$cliente_data = $this->model_users->lettura_dati($clienteemail);
$cliente['nome'] = $cliente_data['nome'];
instead of:
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
I have been trying to figure out how to load the data in a query to an array.
$query->row() //only brings back a single row of data when there are more entries in the database.
If I just use a foreach loop and echo in the model code below, The data is simply displayed on the screen. It's not in a variable or an array. It is just text on the screen all jammed together.
I had a really hard time trying to find a code example that would show me how to use the
$this->db->get_where('table' array('column' => $var);
I finally found it but then the example on codeigniters site only echos the query back to the screen.
http://ellislab.com/codeigniter/user-guide/database/results.html
This is not useful for production.
My controller code is:
public function record(){
/*
* Here the id is being passed to the record
* function to retieve the parent and childrens data
*
*/
$getid['id'] = $this->uri->segment(3);
$accld = $getid['id'];
$data = array();
$this->load->model('account');
$account = new Account();
$account->load($getid['id']);
$data['account'] = $account;
$this->load->model('children');
$children = new Children();
$children->accld($getid['id']);
$data['children'] = $children;
$this->load->view('childeditdisplay', $data );
}
}
My Model code is this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$c_data = array();
foreach ($query->result() as $row){
$c_data[] = $row ;
}
return $c_data;
/*
* Note:
* I need to figure out how to load to an array to pass back to the
* controller to pass to the display
* I can echo to the screen the results but that is uncontrolled.
*
*/
}
If I do this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
foreach ($query->result() as $row){
echo $row->id ;
// and all the other fields below here
}
}
My rows are echoed to the screen. But there is no control. So any help in getting control of my data would be greatly appreciated.
ANSWER
This is finally what worked to bring back all the results and not just one row.
/**
* Populate from an array or standard class.
* #param mixed $row
*/
public function populate($row) {
foreach ($row as $key => $value) {
$this->$key = $value;
}
}
public function accld($id) {
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$this->populate($query->result());
}
Just do
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$_array = $query->result_array();
Do whatever with $_array.
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,
)
);