Get All Indexes Of array in codeigniter - php

Here Is MY Output OF problem i want to get all reciver_id indexes from this array and after getting all indexes i want to get the result from another table users against these id's
$data['cat_row'] = $this->messages_model->get_sentnotify($user_id);
foreach($data['cat_row'] as $key){
$profile = $key['reciver_id'];
}
$data['profile'] = $this->messages_model->Sender_profile($profile);
through this code i get only 1 value of first index how to get all...
getting all i want to get users from other table against each id
function Sender_profile($profile)
{
$this->db->where('id', $profile);
$query = $this->db->get($this->db_table2);
return $query->result_array();
}
kindly help me about sql also how i get all values from database in one iteration

Code Part 1
Get all reciver_id in an array like follows:
$data['cat_row'] = $this->messages_model->get_sentnotify($user_id);
$profile = [];
foreach($data['cat_row'] as $key){
array_push($profile, $key['reciver_id']);
}
$data['profile'] = $this->messages_model->Sender_profile($profile);
Code Part 2
Use Codeigniter's where_in() function.
function Sender_profile($profile) {
$this->db->where_in('id', $profile);
$query = $this->db->get($this->db_table2);
return $query->result_array();
}

In your controller , you need to access all your receiver_id then modify your foreach loop:
$i=0;
foreach($data['cat_row'] as $key){
$profile[$i] = $key['reciver_id'];
$i++;
}
Now you have all your receiver_id in $profile array. and pass this array in controller function and should query like this:
SELECT * FROM table WHERE id IN (5,4,3,1,6);// Just for example you need to modify your query according to your need.

Related

Print count value in codeigniter

I want to print count of some records in my project , i tried using some code but no result is giving can anyone figure out the mistake please.
controller
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->result();
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}
Model
public function c_count($sess)
{
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
return $query;
}
View
<?php foreach($count as $count){echo $count;}?>
I see your query using count and where. That is mean you just select 1 row of data like this.
username COUNT(product_id)
admin 3
The return data is just 1 row, so you can return the data using row() like this return $query->row().
Model : return your data default as a row() for 1 row of data.
public function c_count($sess)
{
$query = $this->db->query("SELECT COUNT(product_id) as count_id
FROM cart
WHERE username = '$sess'");
return $query->row();
}
Controller : Call your data here.
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->count_id; // CHANGE FROM $data['count'] = $query->result();
// If you dont mind, I change your code :
// $query = $this->db->get("cart");
// $data['records'] = $query->result();
$record = $this->db->get("cart");
$data['records'] = $record->result();
$this->load->view('frontend/menu',$data);
}
Views Here is how to call your data, ill give example using <span>.
<span>Admin total product : <?php echo $count; ?> Products</span>
There is so many ways to call returned data from database.
You can also use <?php echo $query->count_id; ?> in your views without set it into $data['count'] in your controller. You can try it now. :) Hope this help.
Note : If you want to call more than 1 data, dont use where but use a group by. I want to give you an example for that, but it's a different problem with your question. :) and if there any typos, please let me know and I will fix it.
$query =$this->db->query("SELECT COUNT(`product_id`) AS count FROM `cart` WHERE
`username`='$sess'");
change the query to
$query =$this->db->query("SELECT COUNT(`product_id`) as count FROM `cart` WHERE `username`='$sess'");
$query->result() will return array of objects
in view you will get as object you can use
<?php foreach($count as $count){echo $count->count;}?>
or
<?php echo $count[0]->count?>
The issue is with your model class where you fetch the number of row counts.
Actually, in CodeIgniter the result set fetched matches with what the columns of DB tables are.For eg. the statement
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
will return a result set something like this
Array ( [0] => stdClass Object ( [COUNT(`product_id`)] => 60 ) )
And when you try to display the result with this line <?php foreach($count as $count){echo $count;}?>
you get error because you are asking to show $count data variable of $count array which is not present.
One simple trick to solve this problem without much changes in your code is to use alias in your query.Just change your query to this
$query =$this->db->query("SELECT COUNT(`product_id`) as 'nums' FROM `products` WHERE `service_id`='$sess'");
And fetch the result in the view as <?php foreach($count as $c){echo $c->nums;}?>
However,in my opinion its better to use inbuilt function num_rows() of CI for this.
Simply use PHP count() function after getting the result
CONTROLLER
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = count($query->result());
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}

return the columns of a result row as an array that can be referenced by index in codeigniter / active record

I am getting a specific row in a database with codeigniter / php /active record. I a would like to return the result as an array of the row's columns that can be referenced like this:
result[0] = column1
result[1] = column2
...
This is my current query:
public function get_instance($instanceID = NULL){
$this->db->select('organism, feature, goal');
$this->db->from('extra_instances');
$this->db->where('id', $instanceID);
$query = $this->db->get();
return $query->row_array();
}
$data['instance'] = $this->instances_model->get_instance($instanceID);
But currently, to echo these, I (think) I need to give the name of the column, like:
<?php echo($instance['goal']) ; ?>
Is there a way to do this so I can say:
<?php echo($instance[2]) ; ?>
You can do this by create a new array and assigns all values of old array to new array.
You can use the array_values() function to do this.
Here is the example. so you can get more idea.
public function get_instance($instanceID = NULL){
$this->db->select('organism, feature, goal');
$this->db->from('extra_instances');
$this->db->where('id', $instanceID);
$query = $this->db->get();
$results = $query->row_array();
return array_values($results);
}

One dimensional array results from SQL column

SELECT col FROM table
Say I have this query and I get the following result:
array(2) {
0 => array(1){
"COL"=>"value1"
},
1 => array(1){
"COL"=>"value2"
}
}
Is there some SQL statement I can use to get this from the same data:
array(2) {
0=>"value1",
1=>"value2"
}
I'm using zend framework and db2. If it can't be done through SQL, can it be done with Zend?
Thanks
EDIT: I should clarify, I can do this with a loop or a function. I was just wondering if there was a built-in way to do it to save a few lines of code and be all fancy smartpants.
you could try the fetchPairs() method. That might be what you're looking for, at least in a limited fashion.
The fetchPairs() method returns data in an array of key-value pairs,
as an associative array with a single entry per row. The key of this
associative array is taken from the first column returned by the
SELECT query. The value is taken from the second column returned by
the SELECT query. Any other columns returned by the query are
discarded.
You may also try and set the fetch method to Zend_Db::FETCH_COLUMN.
Zend_Db::FETCH_COLUMN: return data in an array of values. The value in
each array is the value returned by one column of the result set. By
default, this is the first column, indexed by 0.
$db->setFetchMode(Zend_Db::FETCH_COLUMN);
try a custom function like this:-
function myfuntion($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, myfuntion($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Here is how I do it:
in my model:
public function getRecords() {
$select = $this->select();
return $this->fetchAll($select);
}
in my controller:
$records = $mdl->getRecords();
$recordsArray = $records->toArray();
I think the easiest way is :
public function my_function()
{
$db = Zend_Db_Table::getDefaultAdapter();
$results = $db->fetchAll("SELECT * FROM my_table");
/* if you want only one row, do something like this*/
/* $results = $db->fetchRow("SELECT * FROM my_table") */
return $results;
}
/* Then maybe in your controller you can call the function
and */
$results=my_function();
/*make values avelaible to the view*/
$this->view->$results=$results
Then inside the view : it depends on what your function resturns:
case: its fetchAll:
<?php foreach ($this->results as $item): ?>
<?=$item['address']?> /* access fields */
<?php endforeach ?>
case: its fetchRow: No need to use foreach().
I hope it helps.

return variables from array using a function

I retrieve data from database using this query:
SELECT * FROM tickets_departement_groups WHERE group_id = '{$user_group}'
$user_group is already defined, and I fetch the data using mysql_fetch_array, like this:
foreach ($query->result_array() as $row)
{
return $row['departement_id'];
}
All this is under a function called get_departement_id(), So when I do echo get_departement_id();
it prints last departement ID, but I have many of them. What I want to do is to output all the department IDs for a given query.
create and array and return the array?
$id_list = array();
foreach($query->result_array() as $row){
$id_list[] = $row['departement_id'];
}
return $id_list;

MultiDimensional Arrays

In Codeigniter, I have the following model
function get_item_history($id)
{
//from metadata_history get item_id and corresponding metadata
$this->db->from('metadata_history')->where(array('id'=>$id, 'current_revision'=> "TRUE"));
$query = $this->db->get();
$result = $query->result_array(); //store this in an array
// loop through the array
foreach( $result as $key => $row )
{
$array = array('item_id'=>$row['item_id'], 'current_revision'=> "TRUE");
$this->db->from('history')->where($array);
$query = $this->db->get();
$row['items'] = $query->result_array(); //
$result[$key] = $row;
}
return $result;
}
The problem is that this results in multiple queries to the SQL table increasing the execution time significantly (pagination is not an option)
I want to be able to pass the first query results to the second query as an array, so that I would have only a single go at the database, then rebuild an array from the results.
How should I rewrite this code (the second part)? Will it be faster (I suppose so)?
EDIT
Rebuilding the array from the results is what is flummoxing me.
http://www.phpbuilder.com/board/showthread.php?t=10373847
this is what I probably want, but am failing the jump
You can use inner query here. It is ideal situation for that -
function get_item_history($id)
{
// Here the above requirement can be achieved in a single query.
$sql = "select * from history h
where h.item_id IN (select item_id from metadata_history mh where mh.id = $id
AND mh.current_revision = TRUE) AND h.current_revision = TRUE";
$result = $this->db->query($sql);
//Return whichever column of result you want to return or process result if you want.
$result;
}
You should use JOINs to do this. It'll offload the execution of the query to the server. I can't give you too much more detail without knowing how your database is structured, but check out the docs on JOINs:
http://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.webdesign.org/web-programming/php/mysql-join-tutorial.14876.html
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
Another option would be to do your wheres in the loop and move the query executation outside of the foreach:
// loop through the array
foreach( $result as $key => $row )
{
$array = array('item_id'=>$row['item_id'], 'current_revision'=> "TRUE");
$this->db->or_where($array);
}
$query = $this->db->get();
$row['items'] = $query->result_array(); //
$result[$key] = $row;
OK this took some work, and I also had to do some adjustments in my view
So the problem can be broken down into two main components
1) Pass the results of the first query as an array to the second one using where_in
2) Reorder/regroup the results of the first array by item_id
My earlier code was doing the second component implicitly
So here is what I did (limits, offsets, ordering have been cut out to improve readablity)
function get_item_history($id)
{
//from metadata_history get item_id and corresponding metadata
$this->db->from('metadata_history')->where(array('id'=>$id, 'current_revision'=> "TRUE"));
$query = $this->db->get();
$result_query1 = $query->result_array(); //store this in an array
foreach ($result_query1 as $key-> $row){
$result[$row['item_id']]['meta_info'] = $row; //the first query contains meta info, that must be passed to the view
$selected_id_array[] = $row['item_id']; //Create a array to pass on to the next query
$result[$row['item_id']]['items'] = array(); //declare an array which will hold the results of second query later
}
$this->db->select('h.*');
$this->db->from('history h');
$this->db->where_in('h.item_id', $selected_id_array);
$this->db->where(array('h.current_revision' => 'TRUE'));
$query = $this->db->get();
$row = $query->result_array();
foreach ($row as $key => $datarow) {
$result[$datarow['item_id']]['items'][] = $datarow; //populate the array we declared earlier with results from second query
}
return $result; // Now this variable holds an array which is indexed by item id and contains the results of second query 'grouped' by item_id
}
So the number of queries have been cut from ~10 to 2.
On my local machine this saves ~50 msec/page, though I am not sure how this will do for larger databases.

Categories