Codeigniter : array to string conversion error - codeigniter

Here is my model:
public function count_diabetic(){
$query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");
return $query->result_array();
}
public function count_hypertensive(){
$query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");
return $query->result();
}
here is my controller:
public function home(){
$this->load->model('Jsv_model');
$data = array(
'count_diabetic' => $this->Jsv_model->count_diabetic(),
'count_hypertensive' => $this->Jsv_model->count_hypertensive()
);
$this->session->set_userdata($data);
$this->load->view('home');
}
Here is my view with in php tag:
echo $this->session->userdata('count_diabetic');
But Here it shows error that array to string conversion error..
please help me

Inside count_diabetic() you should change $query->result_array()
into
$query->row()->count_diabetic,
it would return number of count only not array.
Do it to count_hypertensive() too.

In PHP, you can display arrays by using the print_r function instead of echo.
For example, you have to change your code to:
print_r($this->session->userdata['count_diabetic']);

You are doing it wrong in this line.
echo $this->session->userdata('count_diabetic');
What should you do?
// To Set a Data in Session
$session_data = array(
'count_diabetic' => $this->Jsv_model->count_diabetic(),
'count_hypertensive' => $this->Jsv_model->count_hypertensive()
);
$this->session->set_userdata('user_data', $session_data);
// To get the session data
$session_data = $this->session->userdata('user_data');
$user_name = $session_data['username'];
$count_diabetic = $session_data['count_diabetic'];
$count_hypertensive = $session_data['count_hypertensive'];

Related

codeigniter get array data in controller

I have sql query in controller, this query produces number of rows.
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->row();
foreach($q1 as $v_barcode){
$result = $this->settings_model->update_cancel_stock($v_barcode->product_code,$v_barcode->product_quantity);
}
then i pass this data to my model,
public function update_cancel_stock($code,$qty)
{
$this->db->set('product_quantity', $qty , FALSE);
$this->db->where('product_id', $order );
$this->db->update("tbl_inventory6");
}
but no any update. please check above code. thanx
Try this
$cond = array("order_id" => $order_no, "location" => $location);
$q1 = $this->db->select("product_code,product_quantity")->from("tbl_order_details")->where($cond)->row();
$result = $this->settings_model->update_cancel_stock($q1->product_code,$q1->product_quantity);
and then model ($code was not used)
public function update_cancel_stock($code,$qty){
$this->db->set('product_quantity', $qty , FALSE);
$this->db->where('product_id', $code);
$this->db->update('tbl_inventory6');
}
You are using row() function of Active Record. It already return only one row. So there is no requirement of foreach. Try this:
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->row();
$result = $this->settings_model->update_cancel_stock($q1->product_code,$q1->product_quantity);
If you are getting multiple records and you are using foreach, you should use result().
$q1 = $this->db->query("SELECT product_code,product_quantity FROM tbl_order_details WHERE order_id='$order_no' AND location='$location'")->result();
foreach($q1 as $v_barcode){
$result = $this->settings_model->update_cancel_stock($v_barcode->product_code,$v_barcode->product_quantity);
}

Codeigniter multiple parameter on update

I am copying this code in Codeigniter official docs, but I don't know why this will throw an error
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->db->where('id', $id);
$this->db->update('change_request',$data);
//return true;
}
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE change_request SET status = 'Y', approve_by = Array WHERE id = '22'
It sounds wierd since this code works in my other function. Any idea?
Read The Documentation Clearly
Read About Update Records In Codeigniter
Here IS Demo Function For You
public function updateBasic($data,$user_id){
$userData=array(
'marital_status'=>$data['marital_status'],
'country'=>$data['stateofresidence'],
'city'=>$data['city'],
'caste'=>$data['caste'],
'residential_status'=>$data['residencystatus']
);
$this->db->WHERE('user_id',$user_id)->update('basic_profile',$userData);
return true;
}
You Must Check Through Print_r();what Is coming To your Function In Your Case $data1 Is Coming In the From OF array You Must Extract The Array To Update The Record
Use this function in your model to update the record.
public function acceptChangeRequest($where, $table, $data){
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows() > 0;
}
use this code in your controller.
$where = array('id'=>$id);
$data = array(
'status' => $accept,
'approve_by' => $data1,
);
$this->User_model->update($where,'table_name',$data);
What is in your $data1 variable? I can see that it's an array, and that is the problem.
If your $data1 stores indexes like in your table's row, than this is the possible solution for you:
public function acceptChangeRequest($id,$data1,$accept) {
$data1["status"] = $accept;
$this->db->where('id', $id);
$this->db->update('change_request', $data1);
return true;
}
But if your $data1 variable stores only the approve_by information, than your possible solution is:
public function acceptChangeRequest($id,$data1,$accept) {
$data = array(
'status' => $accept,
'approve_by' => $data1["approve_by"]
);
$this->db->where('id', $id);
$this->db->update('change_request', $data);
return true;
}
First of all, you need to know what you expect from $data1, than you can move forward to the solution.
You can see your $data1 variable in your Controller's function:
print "<pre>";
print_r($data1);
print "<pre>";
die();

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;}

codeigniter error using JOIN to select single row

Im trying to get joins to work when selecting a single row. here is my code:
model:
function view($id) {
$this->db->select('c.name
,c.phone
,c.active
,c.website
,c.date_acquired
,con.firstName');
$this->db->from('company c');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row_array();
controller:
public function view($id)
{
$this->load->model('Company_model');
$data['data']= $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
the error im getting is:
Fatal error: Call to a member function row_array() on a non-object in
/home/techf/public_html/application/models/company_model.php on line
35
and line 35 in the above code is:
$query = $this->db->get()
is this not correct when dealing with joins and a row array?
**
edit 1
**:
Here is my controller:
public function view($id)
{
$this->load->model('Company_model');
$data = $this->Company_model->view($id)->row();
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
and my model:
function view($id) {
$this->db->select('*');
$this->db->from('company');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
return $this->db->get('company');
}
but now im am getting error:
Fatal error: Call to a member function row() on a non-object in
/home/techf/public_html/application/controllers/company.php on line 21
Here you go model code
public function get_joins($table,$value,$joins,$where,$order_by,$order)
{
$this->db->select($value);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
$this->db->order_by($order_by,$order);
$this->db->where($where);
return $this->db->get($table);
}
and in your controller aceess it like
$value=('restaurantorders.*,restaurant.Name,restaurant.CurrencyId,currency.*,orderpaymentdetail.Gateway ');
$joins = array
(
array
(
'table' => 'tk_restaurant',
'condition' => 'restaurant.Id = restaurantorders.RestaurantId',
'jointype' => 'inner'
),
array
(
'table' => 'tk_currency',
'condition' => 'restaurant.CurrencyId = currency.Id',
'jointype' => 'inner'
),
array
(
'table' => 'tk_orderpaymentdetail',
'condition' => 'restaurantorders.Id = orderpaymentdetail.OrderId',
'jointype' => 'inner'
),
);
$data['order_detail'] = $this->general_model->get_joins($data['tbl'],$value,$joins,array('OrderStatus'=>'Confirm','restaurantorders.Id'=>$orderid),'restaurantorders.Id','desc')->row();
note that on the model i test first if num_rows() is greater than 1 before sending on the row and if not return false.
Note that on my this->db->get i removed the name of the table, because you already added it on the from method.
$this->db->select('*')
->from('company c');
->join('contacts con','c.primary_contact = con.id','left');
->where('id', $id);
$query = $this->db->get();
return $query->num_rows() >= 1 ? $query->row() : FALSE;
on your COntroller
on on the data variable you forgot to add a key, this will be used when you access the variable/object on you're view, example is $data['contacts']
public function view($id)
{
$this->load->model('Company_model');
$data['contacts'] = $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
on your VIEWS
access the contacts key that you assigned earlier on you're controller.
<?
if(!empty($contacts))
{
print_r($contacts);
}else{
echo 'No data';
}
?>
to show the structure of your query on a standard MySQL query
you could comment out the return on you're model and add this snippets of code just after the $this->db->get() method.
echo $this->db->last_query();
die();
This will echo out what query was made, and you can run it on phpmyadmin and compare if the values returned are right.
can you try it like this maybe?
model: (i'm not sure in which table is id and in which primary_contact, so change that if i made a mistake)
function view($id) {
$this->db->join('contacts','company.primary_contact = contacts.id','left')
->where('id', $id);
$query = $this->db->get('company');
return $query->row();
}
in controller call it like this:
$data['result'] = $this->company_model->view($id);
then access object in view:
<?=$result->id?> (etc.)

How to get a value from the last inserted row using Codeigniter

Is there any codeigniter function to do this?
try this code:
$this->db->insert_id();
Refer:
https://www.codeigniter.com/user_guide/database/helpers.html
There is no special function for that. But you can get the id of row that you've just inserted and then get it's data:
$this->db->insert('table_name', $data);
$id = $this->db->insert_id();
$q = $this->db->get_where('table_name', array('id' => $id));
return $q->row();
I have tips for you. When you want to insert data, please return your data array and you can edit it.
public function set_alb_photos() {
$data = array(
'alp_title' => $this->input->post('alp_title'),
'alp_file_location' => $this->input->post('alp_file_location'),
'alp_album_id' => $this->input->get('alb_id'),
'alp_created_at' => date("Y-m-d H:i:s"),
'alp_updated_at' => date("Y-m-d H:i:s")
);
$this->db->insert('alb_photos', $data);
return $data;
}
I hope this help.
Use Active Record method after insertion. return last inserted id
function insert($data)
{
$this->db->insert('tablename', $data);
return $this->db->insert_id();
}
Here is reference
This will help you to get last inserted row from the table.
$last = $this->db->order_by('id',"desc")->limit(1)->get('tablename')->row();
print_r($last);
You can get inserted data by below code,
$query = $this->db->get_where('table1', array('id' => $id)); //get inserted data
return $query->result_array();
Refer:https://www.codeigniter.com/user_guide/database/query_builder.html
What about :
$this->db->get('mytable', 1,0)
Try this only with active record of codeigniter. This code gives you the last row of your table.
$this->db->limit(1);
$this->db->order_by('id','desc');
$query = $this->db->get('tablename');
return $query->result_array();
Try this depending on the options and return :
$data = {} //your array;
// now if your $data array contained all the values of the new row just do this
function yourFunction(){
// insert into array into db
$this->db->insert('table_name', $data);
// get created rows id
$id = $this->db->insert_id();
// update your $data array with the new generated id and return it
$data['id'] = $id;
return $data;
}
// Option 2: if row has fields that auto populates (example current timestamp)
function yourFunctionAlt(){
// insert into array into db
$this->db->insert('table_name', $data);
// get created rows id
$id = $this->db->insert_id();
// get row as a array
$_rowArray = $this-db->get_where('table_name',array('id'=>$id)->row_array();
return $_rowArray;
// or get as a object
$_Object = $this->db->get_where('table_name',array('id'=>$id);
return $_Object;
}

Resources