covert array of object into a single object php - php

This is a headache issue for long time. I have the following code in codeigniter php active record.
$this->db->select('*');
$this->db->from('orders');
$this->db->join('order_detail', 'order_detail.order_id = orders.o_id');
$this->db->join('profiles','profiles.id = orders.buyer_id','left');
$this->db->where('orders.o_id', $order_id);
$this->db->group_by('orders.o_id');
$query = $this->db->get();
$order_details_by_order_id_result = (object)$query->result();
result
var_dump($order_details_by_order_id_result);exit; //see below
object(stdClass)[34]
public 0 =>
object(stdClass)[37]
public 'xx_id' => string '13' (length=2)
public 'yy_iud' => string '22' (length=10)
public 'order_total' => string '25.00' (length=5)
public 'shipto_fname' => string 'dan' (length=3)
public 'shipto_lname' => string 'theman' (length=6
on my controller i called the above function as follow:
$order_details = $this->orderdetails->get_orderdetail_of_buyer($oid);
$data['order_details'] = $order_details; //pass this to the view
$this->load->view('dashboard/order_detail_view',$data);
and i want to send the result to the view (/order_detail_view.php)
Order #o_id ;?>
$order_details->o_id; //why on earth this expression show me error
i guess the problem is
object(stdClass)[34]
public 0 =>
How could i ever solve this because i fetch only one order at a time. Thanks

row() method will return a single row for you query.
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
echo $row->xx_id;
}

In CodeIgniter, $query->result() returns an array of objects, each element represents the row in the result set. No need to convert it into object; use...
$result = $query->result();
if ($result) {
$order_details_by_order_id_result = $result[0];
}
... instead.
For your original code, there's actually no way to get the content object: PHP objects that are results of conversion from array do not play nicely with numeric keys (you can read more about this here).

Related

How to convert a result set to an array of objects with Codeigniter's Active Record? [duplicate]

This question already has answers here:
Codeigniter/PHP: Format db query as an array
(4 answers)
Closed 2 years ago.
This is my controller:
public function index()
{
$data['page_title'] = 'Home';
$data['new_grievances'] = $this->admin_home->get_members();
$data['num_row'] = count($data['new_grievances'] );
print_r($data['new_grievances']);
print_r($data['num_row']);
$this->load->view('admin/grievances_admin_home' , $data);
}
This is my model:
function get_members() {
// $query = $this->db->get('enquiry');
// return $query;
$this->db->from('enquiry a');
$this->db->join('enquiry_department b', 'a.department=b.id' , 'inner');
$this->db->join('enquiry_user_type c', 'a.user_type=c.id' , 'inner');
$this->db->WHERE('a.status IS NULL');
$query = $this->db->get();
return $query;
}
I want to get the rows and and count of the number of rows.
Here, I execute the query $data['new_grievances'] number of rows is 0 and so output of $data['num_row'] must return zero.
When I have a result with at least one row, then I print the $data['new_grievances'] value it gives:
CI_DB_mysqli_result Object (
[conn_id] => mysqli Object (
[affected_rows] => 0
[client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
[client_version] => 50011
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array ( )
[field_count] => 12
[host_info]
...
How do I get the rows in the result set?
Change your code from return $query; to return $query->result(); by this you can also use your $data inside the view also and count the total results in your controller.
This is controller
public function index()
{
$data['page_title'] = 'Home';
$data['new_grievances'] = $this->admin_home->get_members();
$data['num_row'] = count($data['new_grievances'] );
print_r($data['new_grievances']);
print_r($data['num_row']);
$this->load->view('admin/grievances_admin_home' , $data);
}
This is my model
function get_members() {
$this->db->from('enquiry a');
$this->db->join('enquiry_department b', 'a.department=b.id' , 'inner');
$this->db->join('enquiry_user_type c', 'a.user_type=c.id' , 'inner');
$this->db->WHERE('a.status IS NULL');
$query = $this->db->get();
return $query->result();
}
Please follow below lines.
public function index()
{
$data['page_title'] = 'Home';
$new_grievances = $this->admin_home->get_members();
$data['num_row'] = $new_grievances->num_rows();
print_r($new_grievances->result());
$data['new_grievances'] = $new_grievances->result()
print_r($data['num_row']);
$this->load->view('admin/grievances_admin_home' , $data);
}
Simply use the below line to get your results from DB
$query = $this->db->get();
$results = $query->result();
and use the below code to get number of rows found
$count = $query->num_rows();
public function index()
{
$data['page_title'] = 'Home';
$data['new_grievances'] = $this->admin_home->get_members();
/*Old Code
$data['num_row'] = count($data['new_grievances'] );*/
//New Code
$data['num_row'] = $data['new_grievances'];
print_r($data['new_grievances']);
print_r($data['num_row']);
$this->load->view('admin/grievances_admin_home' , $data);
}
Model
function get_members() {
$this->db->from('enquiry a');
$this->db->join('enquiry_department b', 'a.department=b.id' , 'inner');
$this->db->join('enquiry_user_type c', 'a.user_type=c.id' , 'inner');
$this->db->WHERE('a.status IS NULL');
return $this->db->count_all_results();
}
As I said in this similar answer, as long as you are only using the row count in one layer of your MVC structure, there is no real gain in declaring a count variable.
If you are only going to use the value in your View, then only call count() in your View.
If you are only going to use the value in your Controller, then only call count() in your Controller.
If you need the row count in both the Controller AND the View, then write D.R.Y. code and cache the row count as a variable in the Controller, then pass it to the View.
Ultimately, I'm recommending that you not bloat the variable scope with data that is instantly accessible with a O(1) function call.

Why does CodeIgniter return my SQL query as an array, with an object inside?

I have constructed a model within codeigniter named 'Profile_model' which contains the following sql queries, and is supposed to return the user_name of the user with a given id ('userpdata' is the table which contains this info) :
public function get_username($id)
{
$query = $this->db->select('user_name')
->where('id', $id)
->get('userpdata');
return $query->result();
}
I have passed in the $id of the current user from the controller like so (model is referred to as 'profile'):
$userId = strval($this->ion_auth->get_user_id());
$data = array(
'username' => $this->profile->get_username($userId)
);
$this->load->view('user/profile', $data);
user/profile view:
<?php
print_r($username);
?>
This returns the string:
Array ( [0] => stdClass Object ( [user_name] => hish ) )
Which appears to be an array containing an object. How can I retrieve just the user_name 'hish'?
Change $query->result(); to $query->row(); so that you don't get an array. The result() method returns an array of rows, each of which is an object. The row() method returns the first object of the result set.
public function get_username($id)
{
$query = $this->db->select('user_name')
->where('id', $id)
->get('userpdata');
return $query->row();
}
You will end up with the object that contains the property user_name. You could either get the value of it in the controller.
$user = $this->profile->get_username($userId);
$data = array(
'username' => $user->user_name
);
Or you could get it in the view without changing the controller and use this $username->user_name.
Codeigniter - Generating Query Results

How to use "where in" method in codeigniter?

Hello Everybody i have problem with my program i need check multi number in my database but when i test it just show only one result my code :
/*in mt View*/
$data = array(
'name' => 'search_id',
'id' => 'search_id',
'placeholder' => 'numbers_test',
'autofocus' =>"autofocus",
'rows' => '20'
);
echo form_textarea($data,set_value('search_id'));
/* in my model */
$this->db->select('*');
$this->db->from('personal_info');
$this->db->where_in('p_id', $this->input->post('search_id'));
return $this->db->get();
i waiting your help for this problem
If you are getting input as comma separated ids like in string 1,5,4,8 etc from $this->input->post('search_id') then update your code like this
/* in my model */
$this->db->select('*');
$this->db->from('personal_info');
// Explode string into array to make where_in clause work
$this->db->where_in('p_id', explode(',', $this->input->post('search_id')));
return $this->db->get();
as official docs suggest you need to provide array of options in IN clause
You have to return the result of the query. Make changes,
/* In my model */
$this->db->select('*');
$this->db->from('personal_info');
$this->db->where_in('p_id', $this->input->post('search_id'));
$query = $this->db->get();
return $query->result_array(); // You've to return the result of the query
Also as #Saqueib said in comments, try some debugging when in doubt,
echo $this->db->last_query(); exit;
OR
echo '<pre>'; print_r($query->result_array()); exit;

codeigniter unit testing queries

I'm new to codeIgniter and unit test, and i want to test this query that return a multidimentionnal array
public function get_ficheFrais($selected_visiteur_np) {
$query = $this->db->select('ff.mois')
->from('fichefrais ff')
->join('utilisateur u', 'u.id = ff.idVisiteur', 'inner')
->where('ff.idVisiteur', $selected_visiteur_np)
->where('ff.idEtat', 'VA')
->get();
return $query->result();
}
this is the var_dump of the query:
array (size=1)
0 =>
object(stdClass)[42]
public 'mois' => string '201211' (length=6)
but i can't find out how to write it in the test function. i've tried this:
$this->visiteur_model->get_ficheFrais('a131');
$data['ficheFrais'] = $this->visiteur_model->get_ficheFrais('a55');
$this->unit->run($data['ficheFrais'], (array ('mois'=>'201211')), "testing get_ficheFrais function");
$this->load->view('visiteur/v_tests');
can anyone help or has a better solution on how to test queries that return arrays?
I think were you are going wrong is you are expecting your get_ficheFrais function to return an array but its actually returning an object. If you want it to return an array you want to change it from
return $query->result();
to
return $query->result_array();
So bearing in mind it returns an object at the moment you want to change your unit test to
$this->unit->run($data['ficheFrais']->mois, 201211, "testing get_ficheFrais function");

How do I pass data from my model to my view as an object and as an array?

I have the following query, which returns a single row.
MODEL:
function get_guide_first(){
$this->db
->select('*')
->from('guides_entries')
->order_by("guide_name", "asc")
->limit(1, 0)
->join('guides_content', 'guides_content.guide_id = guides_entries.guide_id');
$query = $this->db->get();
return $query->result_array();
}
Here is my controller:
CONTROLLER:
public function get_first_guide(){
$page_data['guide']=$this->guides_model->get_guide_first();
$this->load->view('guidepage', $page_data);
}
I then run a foreach() loop in my view (or controller sometimes).
VIEW:
foreach($guide as $row){
echo $row['guide_content'];
$activecat=$row['guide_slug'];
}
Now what I would ideally like to do is return an array back from my model but even using:
return $query->row();
returns an object rather than an array.
1)How can I return this row as a 2d array?
e.g. so that I could echo a result in the controller as guide['col_name'] rather than guide()->col_name.
2)how would I pass the object to my view so that I could use $guide->col_name from there (I would need to pass this along eith the $page_data array)
If i'm reading your question right: You can use row_array instead of result_array
I think:
return $query->result_array();
returns an
array(
0 => array(
'blah' => 'blah',
'smile' => 'smile'
)
);
to return just an associated array.
row array will return
array(
'blah' => 'blah',
'smile' => 'smile'
)
Use row_array() in your model.. that will retrun associated array.
function get_guide_first(){
$this->db
->select('*')
->from('guides_entries')
->order_by("guide_name", "asc")
->limit(1, 0)
->join('guides_content', 'guides_content.guide_id = guides_entries.guide_id');
$query = $this->db->get();
return $query->row_array();
}

Categories