how to do foreach in codeigniter controller I want to run a select query in the codeigniter 3 controller with foreach and do the calculations for the data, then it will insert into the table
Asked
Active
Viewed 56 times
-1
-
Related: [Pass array from controller to view - Codeigniter](https://stackoverflow.com/q/13387729/2943403) and [codeigniter passing array data from model to controller](https://stackoverflow.com/q/14121978/2943403) – mickmackusa Apr 26 '23 at 05:06
2 Answers
2
Write your select method in your model
public function get_all_rows()
{
$query = $this->db->get('table_name');
return $query->result_array();
}
and then you can call and iterate it in your controller like this:
$this->load->model('my_model');
$data = $this->my_model->get_all_rows();
foreach($data as $item)
{
echo $item['name'];
}
Also you can see this link for more information: https://codeigniter.com/userguide3/tutorial/news_section.html

Karim Pazoki
- 951
- 1
- 13
- 34
-
Of course a controller should be passing data to a view for displaying purposes. In the model, `$query` never needs to be defined; it will be simpler to just chain the `result_array()` call to the `get()` call. – mickmackusa Apr 26 '23 at 05:01
0
In my humble opinion, you have to understand the concept of MVC in Codeigniter firstly
you can learn it in this link for complete information https://www.codeigniter.com/userguide3/overview/mvc.html
For your case maybe you can write like code below, of course must be adjusted to your needs
$data = array();
# call model method
$dataA = $this->YourModelClassName->getAllDataFromTable_A();
# check if not empty
if (!empty($dataA)) {
# do looping
foreach ($dataA as $key => $val) {
# just example, maybe you want encode the Id field
$dataA[$key]['id'] = $this->encrypt->encode($val['id']);
# do some calculation as you want here, this is just example
$dataA[$key]['calculation'] = ($val['field_A'] + $val['field_B']) * $val['field_C'];
}
$data['data_A'] = $dataA;
}
# send to view if you want
$this->load->view('your_view_name', $data);
# but if you wanna save it to table you just add some insert or update data instruction
Hopefully it can help you

amncode
- 1
- 4
-
In my humble opinion, there is no need for `!empty()` because the data returned from the model method is expected to be an empty or populated array. This means that it can be passed unconditionally to the `foreach()` loop. – mickmackusa Apr 26 '23 at 05:03