Getting data from model to controller - codeigniter

I do have a question : I cannot pass the data from model to controller
You can see some of my codes, please help me.
It does not work!
this is my model "mymodel.php"
....
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
if($query){
foreach ($query->result() as $row);
}
$t = "EXAMPLE/{$row->code}";
function wandad() {
return $t;
}
.....
and this is my controller mycont.php
...
$this->load->model('mymodel');
$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
...
and this is my view myview.php
....
echo $new;
.....

Clearly you The model is not written properly and to corrent this simple do this
1.) I put a default value on $t
2.) I put the query >> loop on the inside function
wandad
so it can be executed once called from controller
function wandad() {
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
$t = "";
if($query){
foreach ($query->result() as $row){
$t = "EXAMPLE/{$row->code}".'<br>';
}
}
return $t;
}

Here are several issues into your model
Your Foreach function doesn't do anything
$t is not in the same namespace than wandad()
Function wandad is not defined into your model class
I'm not sure of what you wanna get with wandad() function but here's a pattern.
function yourFunction()
{
/* This will return the full query as an array */
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
/* Store variable in the same class */
$this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
return $this->t;
}
Then into your controller, do that instead :
$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);

#Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.

There is a small mistake in your code #Ernesto.that is
foreach ($query->result() as $row){
$t. = "EXAMPLE/{$row->code}".'<br>';
}
but your code was simply nice

Related

get all data count from relationship | Laravel

i use laravel:command for function, which is i need to know how many reviews been given to my products, i will capture my database example below:
Product fields
Reviews fields
i've already declare the relationship which is:
App\Models\Product :
public function rev()
{
return $this->hasMany(Reviews::class, 'product_id', 'id');
}
App\Models\Review :
public function prod()
{
return $this->belongsTo(Products::class, 'product_id','id');
}
and this is my command for the function:
protected $signature = 'review:product {product_id}';
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
foreach ($products as $key => $value) {
$rating = $value->rev->rating;
}
dd($products);
}
after i run my command it returns this error
Error
what i'm expecting is i could get the whole rating of specific id
You did not declare the variable $rating prior to using it.
But there is a much easier approach to your problem, since youve already setup the relationships.
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::find($id);
$ratings = $products->rev->pluck('rating');
dd($ratings);
}
Because of product can have many revs, so you can use loop for this
foreach ($value->rev as $item) {
$val = $item->rating;
}
if you are expecting to sum up all rating for particular product id, then you should declare initial number for variable $rating before foreach, then sum up with += operator :
public function handle(){
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
$rating = 0;
foreach ($products as $key => $value) {
$rating += $value->rev->rating;
}
dd($rating);
}

what is the model code to fetch multiple result set from store procedure in codeigniter?

My Model code is given below.
public function getattendence($data)
{
$sql="CALL `sp_AttendanceDetails`(?,?,?);";
$query=$this->db->query($sql,$data);
return $query->result_array();
}
But it return one result set.The second result set i not get..
Pass data like this
public function getattendence($data)
{
# example of your $data array
$id = $data['id'];
$name = $data['name'];
$date = $data['date'];
$sql="CALL sp_AttendanceDetails($id,'$name',$date);";
$query=$this->db->query($sql);
return $query->result_array();
}
Use return $this->_execute_multi_query($sql);
refer http://php.net/manual/en/mysqli.multi-query.php

Call to a member function row() on a non-object

i am getting error Call to a member function row() on a non-object in codeigniter my controller is
public function edit_survey_pro($id)
{
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (sizeof($survey) == 0) $this->template->error(lang("error_32"));
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
}
my model is
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
{
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
$this->db->limit($perpage,$start);
if($where){
$this->db->where($where);
}
if($order_by){
$this->db->order_by($order_by);
}
if($arr=='')
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
if(!empty($query))
if($perpage != 0 && $perpage != NULL)
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
here loadContent() is just load the content with view path
public function loadContent($view,$data=array(),$die=0){
//something to load the content
}
in my model I am getting the result as an array of object in $query and then it is returned as $result like this -
$query = $this->db->get()->result(); but at the controller $survey stores array of object and i want to show the content of that array of object ,previously I use
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
to get that data but the problem is $survey->row() cannot return that data bcoz it is not an object it is array of object so it can't be returned through row() method
so instead of this I just call the first element of that data like this-
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey[0]
)
);
Somehow its works for me bcoz I want to show the first row of the data
if sembody wants to show all data then I think he shuld try logic to increment the key value of that array of object for me it is $survey[] you can use foreach loop for increment the of value of the key element
The problems i see are your model, I will dissect it and add comments to your original code to point out the issues:
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
//above there are problems, you are setting some of your parameters to
//equal blank, but below, in your conditionals, you are checking if they
// exist. They will always exist if they are set to blank. Fix them by
// setting them = NULL like this:
// get($table,$where=null,$perpage=0,$start=0,$order_by=null,$arr=null)
{
$this->db->select();// <-- you forgot this
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
//when will $perpage = null? , if never, then you dont need it.
$this->db->limit($perpage,$start);
if($where){
//change this to if(isset($where)). Also why do you use
//curly braces here, but not in the above if statement if only
//one line is affected in your if. I would remove the
//curly braces here.
$this->db->where($where);
}
if($order_by){
// change this to if(isset($order_by)). Same thing as
//above about the curly braces here
$this->db->order_by($order_by);
}
if($arr=='')
// change this to if(isset($arr)).
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
//change this to: $query = $this->db->get()->result_array();
if(!empty($query))
//change the above to if($query->num_rows > 0). Also, here since
//your code body is longer then one line, you will need curly braces
//around your if statement
if($perpage != 0 && $perpage != NULL)
//again, will $perpage ever be NULL? However, why do you need
//this conditional at all, if the limit above is already
//doing this job?
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
after applying all the changes:
MODEL:
function get($table, $where=null, $perpage=0, $start=0, $order_by=null, $arr=null)
{
$this->db->select();
$this->db->from($table);
if($perpage != 0)
$this->db->limit($perpage, $start);
if(isset($where))
$this->db->where($where);
if(isset($order_by))
$this->db->order_by($order_by);
if(isset($arr)) {
$result = $this->db->get()->result_array();
} else {
$result = $this->db->get()->result();
}
return $result;
}
CONTROLLER
public function edit_survey_pro($id) {
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (!$survey) {
$this->template->error(lang("error_32"));
} else {
$data["survey"] = $survey;
$this->template->loadContent("user/edit_survey_pro", $data);
}
}
I think when you use $this->db->get(), you need to pass the table name as param like this:
$this->db->get('table_name')->result();

CodeIgniter pass variables form controller to model

Ok I want to pass two variables from a controller to a model but I get some kind of error. Am I passing variables on right way? My syntax is:
Controller:
public function add_tag(){
if(isset($_POST['id_slike']) && isset($_POST['id_taga'])){
$slika = $_POST['id_slike'];
$tag = $_POST['id_taga'];
$this->load->model("Member_model");
$res = $this->Member_model->add_tags($slike, $tag);
foreach ($res->result() as $r){
echo $r->name;
}
}
else{
echo "";
}
}
Model:
public function add_tags(){
$data = array(
'tags_id' => $tag ,
'photos_id' => $slika
);
$check = $this->db->query("SELECT tags_id,photos_id FROM bridge WHERE bridge.tags_id='{$tag}' AND bridge.photos_id={$slika} ");
if($check->num_rows()==0){
$this->db->insert('bridge',$data);
$res = $this->db->query("SELECT name FROM tags where `tags`.`id`='{$tag}' ");
return $res;
}
}
you are passing variables correctly, but do not get them correctly in the model, which should look like this:
public function add_tags($slike, $tag){
//your other code
}
The following code write on the controller file:-
$data = array();
$this->load->model('dbmodel');
$data['item'] = $this->dbmodel->getData('*','catagory',array('cat_id'=>21));
$this->load->view('listing_view', $data);
The following code write on the dbmodel file:-
public function getData($cols, $table, $where=array()){
$this->db->select($cols);
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
$result = $query->result();
return $result;}

How can I use CodeIgniter form dropdown function?

codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?
Let's say you want a dropdown of items, using result_array():
$query = $this->db->query("SELECT id, item_name FROM items");
$options = array();
foreach ($query->result_array() as $row){
$options[$row['id']] = $row['item_name'];
}
echo form_dropdown('my_items_dropdown', $options, '1');
I have extended the class DB_result.php in system/database with this new function
public function dropdown_array($id_field = FALSE, $list_field = FALSE)
{
$result = array();
if ($id_field === FALSE || $list_field === FALSE) return $result;
$array = $this->result_array();
foreach ($array as $value) {
$result[$value[$id_field]] = $value[$list_field];
}
return $result;
}
Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:
$customers = $this->db->get('customers');
$result = $customers->dropdown_array('id', 'name');
return $result;

Resources