Codeigniter/PHP: Format db query as an array - php

$this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
$data['user_individual'] = $this->db->get();
If this is my db query, how do I get an array of one db row...
ie. I want to do something like $data['user_individual']['id']->format_as_array...

CodeIgniter provides several methods to perform on query results.
See here: https://codeigniter.com/user_guide/database/results.html
result() returns an array of PHP objects.
row() returns a single PHP object for that row.
result_array() returns an array of arrays.
row_array() returns a single array for that row.
row() and row_array() optionally take a parameter which is the number of the row you'd like to return.
Beyond this, it's difficult to tell exactly what you're asking for. You should be able to get your data out exactly as you like with these methods.
Edit:
Incidentally, the way to access these methods is through the query object returned from the $this->db->get() call:
$query = $this->db->get();
$rows = $query->result(); //array of objects
$rows_array = $query->result_array(); //array of arrays
$row = $query->row(); //single object
$row_array = $query->row_array(); //single array

When you use $this->db->get(); you can use $this->db->result(); which returns an arrayobject.
$query = $this->db->get('table_name');
foreach ($query->result() as $row)
{
echo $row->title;
}
See: http://codeigniter.com/user_guide/database/results.html for details on how to obtain resultsets from the database.

Instead of $ this-> db-> get () use $ this-> db-> row_array ();
$this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
$data['user_individual'] = $this->db->row_array();

/**
* format_database_array
*
* Lets you format the database object data to array
#access public
#param String $db_object : database query object
#return String : Return array with data
*/
if ( ! function_exists('format_database_array'))
{
function format_database_array($db_object)
{
$db_array = array();
if($db_object-> num_rows >0)
{
foreach ($db_object->result_array() as $row)
{
foreach ($row as $key => $value)
{
$db_array[$key] = $value;
}
}
}
return $db_array;
}
}

Related

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.

PHP PDO FetchAll arguments to remove row number from results

I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}

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