I am having a problem, which I hope someone could help me with.
I am using CodeIgniter to pull results from a database, and I would like to add these results together. I am not much of a PHP developer, so I am not too sure where to start.
This is the function I am using;
function get_warranty($id) {
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
return $query->result();
}
This function, returns this;
[warranty] = Array
(
[0] => stdClass Object
(
[warranty] => 2
)
[1] => stdClass Object
(
[warranty] => 5000
)
)
But, I would like it to return this;
[warranty] = 5002;
So, it simply adds up each result it finds.
Any help at all, would be greatly appreciated, as I say, I'm not much of a PHP developer, so I don't even know where to start.
Thanks in advance!
The $query -> result() function returns an array of objects with query results...
See documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select
This is the modified function I propose, which simply returns an integer with the total sum, as you need:
function get_warranty($id) {
// Query composition
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
// Iterate through the returned objects and accumulation in $warranty
foreach ($query->result() as $row) {
$warranty += $row->warranty;
}
return $warranty;
}
Kind regards.
In place of return $query->result(); use return $query->result_array();. You will get returned with pure array.
Now you can use foreach loop to add the values up like this:
$add_up = 0;
foreach ($reulst_array as $values)
{
$addup = $add_up + $values;
}
This way variable $add_up will contain the added array.
Related
I have an sql query which returns values. I would want to add new values with keys so that I can use it to my next controller which is these values doesn't come from the query result.
My Model:
$paymentDetails = $this->db->query($sql);
$payments = $paymentDetails->result();
//these are the values I wanted to add to the result for the $payments
$amountDue = 'Sample';
$change = 'Sample';
$result = array_merge($payments, array(
"AmountDue" => $amountDue,
"Change" => $change
));
if($result){
return $result;
}else{
return false;
}
I wonder why array_merge() doesn't work. In my view, values fetched from the SQL Query did returned, but the added (AmountDue and Change) is not found.
Please help me. Thank you so much! Ya'll be a big help for my project. :)
because result() function returns the query result as an array of objects, or an empty array on failure. It is just an alias of result_object().
You have to use result_array() which returns the query result as a pure array.
I hope this will help you.
I'm trying to create pagination in codeigniter and I have it working, but I have a small issue. It seems to be loading all the entries in my database and not the selected ones I want.
public function original_count() {
$this->db->where('type', 'Original');
return $this->db->count_all("story_tbl");
}
I know that whats happening is that the last line is overrighting my previous statements. I can't seem to find a way around it though. I tried just a staight sql statement and then returning it, but I could not get that to work either.
this was my statement...
SELECT COUNT(*) FROM story_tbl where type = 'Original';
Some help would much appreciated! :)
CI has inbuilt count method
count_all_results()
Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:
https://www.codeigniter.com/userguide2/database/active_record.html
$total_count = $this->db->count_all_results('story_tbl', array('type' =>'Original'));
You could also use the built-in num_rows() function...
$query = $this->db->where('type', 'original')->get('story_tbl');
return $query->num_rows();
First Try this one.
$query = $this->db->where('tbl_field', 'value')
->get('your_table');
return $query->num_rows();
Besides this Codeigniter has it own function like the following.
$this->db->where('tbl_field', 'value')
->get('your_table');
return $this->db->count_all_results();
Or use this.
return $this->db->count_all('your_table');
Where wont work on count_all condition.. you can use below method to find out total number of rows..
public function count_all() {
$this->db->select ( 'COUNT(*) AS `numrows`' );
$this->db->where ( array (
'type' => 'Original'
) );
$query = $this->db->get ( 'story_tbl' );
return $query->row ()->numrows;
}
I'm trying to populate a multiselect in my view with the results from a query to the database. Sorry if this is a very basic question—I'm a bit new to CodeIgniter and MVC.
My model simply gets all records from a table:
function getAll() {
$query = $this->db->get('example');
return $query->result_array();
}
I then hope to pass the results to my view to populate a multiselect form element. However, the associative array that is returned does not provide the results I'd like.
What I get:
[0] Array
(
[id] => 6
[name] => Bob
What I'd like to get:
[0] Array
(
[6] => Bob
[7] => Linda
Am I missing something with my query that would achieve my desired results? Should I just use a foreach to create a new array that will be formatted the way I would like? If so would this foreach belong in my controller or view.
Thank you for your help.
Try this:
function getAll()
{
$items = $this->db->get('example')->result_array();
if(empty($items))
return array();
$res = array();
$i = 0;
while($i < count($items))
{
$res[$items[$i]['id']] = $items[$i]['name'];
++$i;
}
return array($res);
}
The most efficient way would be to use active record, because it just gets the data from the column 'name' in your table)
$this->db->select('name')
->from('example');
return $this->db->get()->result();
If you were going to use a foreach loop, if you process the results in the controller you would have to process them again in the view, so you may as well send the entire result array to the view and process them in the view. This is useful if you need to use most of the columns of one particular table in your view.
I use both result() and result_array().
Usually i like to get my result as array thats why i use result_array() mostly..
But i want to know which is the better approach that i should follow,
Which one of them is more efficient to use in regards to performance?
Here is the Example i am talking about in codeigniter queries
$query = $this->db->get();
$result = $query->result_array();
or is this should be the better approach??
$query = $this->db->get();
$result = $query->result();
also right now i am using result_array in my generic model.
Result has an optional $type parameter which decides what type of result is returned. By default ($type = "object"), it returns an object (result_object()). It can be set to "array", then it will return an array of result, that being equivalent of caling result_array(). The third version accepts a custom class to use as a result object.
The code from CodeIgniter:
/**
* Query result. Acts as a wrapper function for the following functions.
*
* #param string $type 'object', 'array' or a custom class name
* #return array
*/
public function result($type = 'object')
{
if ($type === 'array')
{
return $this->result_array();
}
elseif ($type === 'object')
{
return $this->result_object();
}
else
{
return $this->custom_result_object($type);
}
}
Arrays are technically faster, but they are not objects. It depends where do you want to use the result. Most of the time, arrays are sufficient.
for the sake of reference:
// $query->result_object() === $query->result()
// returns:
Array ( [0] => stdClass Object ( [col_A] => val_1A , [col_B] => val_1B , ... )
[0] => stdClass Object ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
// $query->result_array() !== $query->result()
// returns:
Array ( [0] => Array ( [col_A] => val_1A , [col_B] => val_1B , ... )
[1] => Array ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
codeigniter docs for result(), and result_array()
result_array() is faster,
result() is easier
result() returns Object type data.
.
.
.
result_array() returns Associative Array type data.
Returning pure array is slightly faster than returning an array of objects.
result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance. There is very little difference in speed though.
result_array() returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance.
in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON
So I have a variable and a recordset:
$firstRecordID = 1;
$records = Recordset::all();
I want to filter the recordset:
$filteredRecords = $records->find(function($record){
if($record->id == $firstRecordID)
return true;
else
return false;
});
Unfortunately, the closure has no clue what $firstRecordID is.
How do I pass in the ID?
You can bind the $firstRecordID to the closure:
$firstRecordID = 1;
$records = Recordset::all();
$filterFunction = function ($record) use ($firstRecordID) {
return ($record->id == $firstRecordID);
};
$filteredRecords = $records->find($filterFunction);
I also simplified your lambda into a single line.
It is maybe a stupid question, but why are you getting everything to filter afterwards manually when the ODM can do that directly?
$records = Recordset::all(array(
'conditions' => array(
'id' => array('<>' => $firstRecordID)
)
));
Even if the result isn't much smaller that doing all() it looks much cleaner using the right tool for the right purpose.