Codeigniter Get Nested Hierarchical Data from Database - codeigniter

How can i get Hierarchical Data from db in Codeigniter. I read this :
http://www.sitepoint.com/hierarchical-data-database/
And i do good that but i cant optimize this tutorial with my model, controler and views
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
I try but dont show sub category:
My model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
Controller :
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
Views:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And output is :
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
When i do this in model all work fine but when i try that to call in controler and loop in view i have result like above example:
This work onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
And like output i have :
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
Any one have solution or example thanks.

Try storing the level value for each category.
In your model:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
In your controller:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
In your view
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>

Related

get the selected value from drop down menu in cakephp 2.x

I am trying to get the selected from a drop down menu. but it returns the index of the selected elements. I want to retrieve the value of that index. I want to get the value of $year. how can I get the value?
Controller that generate the years
<?php
class StockReportConditionsController extends AppController{
public function report() {
$years = array();
for ($i = 0; $i < 4; $i++) {
$year = date("Y");
$year = $year -$i;
$years[$i]=$year;
}
$this->set(compact('years'));
}
View
<h1>Weekly Report</h1>
<table>
<tr>
<th>Year</th>
<th>Stores</th>
<th>Department</th>
</tr>
<?php echo $this->Form->create('StockReport',array('url'=>array('type' => 'get','action'=>'search')));?>
<tr>
<td>
<?php echo $this->Form->input('year',array('type'=>'select','options'=>$years)); ?>
</td>
<td>
<?php echo $this->Form->input('Store.name',array('type'=>'select','options'=>$stores)); ?>
</td>
<td>
<?php echo $this->Form->input('StockReportCondition.bu_no',array('type'=>'select','options'=>$departments)); ?>
</td>
</tr>
<?php echo $this->Form->end(__('Search'));?>
</table>
Controller
<?php
class StockReportsController extends AppController{
public function search(){
$year = $this->request->data['StockReport']['year'];
echo $year;
$store_no = $this->request->data['Store']['name'];
echo $store_no;
$dept_no = $this->request->data['StockReportCondition']['bu_no'];
echo $dept_no;
$result = $this->StockReport->find('all',array(
'conditions'=>array('yearweek'=>'', 'bu_no'=>'','tn_no'=>'')
));
}
}
It would seem that there's probably never a useful thing that you could do with the zero-based index of the year, and you'd only ever want the actual year value. If that's the case, then set up your options array so that the index and value are the same:
$years[$year]=$year;

how to retrive data from db to the table using getAll()

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Unit extends CI_Controller {
/*Load supplier default*/
public function index($id='')
{
$this->load->model('Unit_model');
($id!='') ? $data["unit_details"]=$this->Unit_model->get_unit($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('unit/unit_manage', ($id!='') ? $data : '');
$this->load->view('includes/footer');
/*Submit supplier on add/edit */
}
public function post_unit()
{
$this->load->model('Unit_model');
$this->db->trans_begin();
// transaction begin statement
try{ //Use try catch statement here
$this ->db-> trans_complete();
if ($this->input->is_ajax_request()){
$case = $this->input->post('case');
//for both case use insert_customer function
if($case=='edit')
$insert_unit=$this->Unit_model->update_unit();
else
$insert_unit=$this->Unit_model->insert_unit();
$data['insert_unit']=$insert_unit;
//place commit statement
$this ->db-> trans_commit();
}
else
{
// through new exception statement
}
}
catch(Exception $e){ //statement here
// Place roll back statement
$this->db-> trans_rollback();
}
$this->sendData($data);
}
} ?>
This is my controller part.
class Unit_model extends CI_Model
{
protected $strTableName = 'suc_unit';
function __construct()
{
parent::__construct();
$CI = &get_instance();
$this->db->from($this->strTableName);
}
/*Load all details of table*/
function get_all()
{
$query = $this->db->get($this->strTableName);
return $query->result();
}
}
The above is my model... i want disply data in my page using the getAll() declared in the model. The insertion, updation and view should take place in the same page
<table id="tblListOfUnits" class="table table-bordered table-striped">
<tr>
<th style="width: 10px">Sl No</th>
<th>Unit Name</th>
<th>Unit Symbol</th>
<th style="width: 40px">No.Of Decimal</th>
</tr>
<?php
if(isset($units)){
$count = 1;
foreach ($units as $key => $unit) {
?>
<tr id="tr_<?php echo $unit->pk_int_unit_id; ?>">
<td id="tdUntSlNo_<?php echo $unit->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $count; ?>.</a></td>
<td id="tdUntNme_<?php echo $unit->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_name; ?></a></td>
<td id="tdUntSymbl_<?php echo $unit->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->vchr_unit_symbol; ?></a></td>
<td id="tdUntDecml_<?php echo $unit->pk_int_unit_id; ?>"><a href="javascript:unitEdit(<?php echo $unit->pk_int_unit_id; ?>)" ><?php echo $unit->int_no_decimal; ?></a></td>
</tr>
<?php
$count ++;
}
}?>
</table>
this is my view page i want to display data in that table using getAll() statement i wrote in the model. The page contain the add & view page together. please help me to complete my work

How to insert many forms in db using Datatables

I tried to submit many forms with datatables. User has to choose the number ot input rows, in which he can submit some information - it's something like Phpmyadmin when you insert rows in db. Names of the input rows are the same. I use loop to show many rows. But in this way with nested foreach, when I submit info in two rows, in database there are 8 rows. How to do that?
Here's my view:
echo form_open('admin/add_questions/');
?>
<table id='example'>
<thead>
<tr><th>Question</th><th>Code</th><th>Group</th><th>Is_reverse</th></tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php for($i=0; $i<=20; $i++) {
?>
<tr>
<td>
<input type="text" name="question[]" id="add_question_table" />
</td><td>
<input type="text" name="code[]" id="add_question_table" />
</td><td>
<input type="text" name="group[]" id="add_question_table" />
</td><td>
<input type="text" name="is_reverse[]" id="add_question_table" />
</td></tr>
<?php
}
?>
</tbody>
</table>
My Model is:
<?php
class Admin_model extends CI_model {
public function __construct() {
parent:: __construct();
$this->load->database();
$this->load->library('session');
}
public function add_questions() {
$date = new DateTime("now");
foreach($this->input->post('question') as $v) {
foreach($this->input->post('code') as $f) {
foreach($this->input->post('group') as $val) {
$data = array(
'question'=>$v ,
'code'=>$f,
'survey_id'=>$this->uri->segment(3),
'group_id'=>$val,
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('survey_questions',$data);
}
}
}
What's the way to do it? :)
Hi from my perspective its best to pass $_POST as a parameter to your add_questions() model method. You may try the following approach :)
//controller code
$this->admin_model->add_questions($_POST);
//model code
function add_questions($data=array())
{
if(count($data) > 0)
{
$date = new DateTime("now");
for($i=0;$i<count($data['question']);$i++){
$insert = array();
$insert['question'] = $data['question'][$i];
$insert['code'] = $data['code'][$i];
$insert['survey_id'] = $data['survey_id'][$i];
$insert['group_id'] = $data['group_id'][$i];
$insert['created_at'] = $date->format('Y-m-d H:i:s');
$this->db->insert('survey_questions',$insert);
}
}
}

how to get result of query in view in codeigniter

I have use two query to get result on the view.
To get the result of resultq1 i use foreach but how can i get result of resultq2 in view.
For each row of resultq1 i get record "reccount" in resultq2.
//controller
//Query 1
$q = $this->db->select(array(
'spf.id as id' ,
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1= $q->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();
$i=0;
foreach($resultq1 as $rec)
{
//query 2
$id = $rec['id'];
$q1 = $this->db->select("count('id') as reccount ")->from('sp_forum_topic spft')->where('spft.forumid',$id)->get();
$resultq2[$i] = $q1->row_object();
$i++;
}
$this->load->view('forumview', $data, true);
//view file
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >---- </td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
Array print in view for resultq2.
Resultq1 have 4 rows so that i get 4 value in resultq2.
Array ( [0] => stdClass Object ( [reccount] => 0 ) [1] => stdClass Object ( [reccount] => 0 ) [2] => stdClass Object ( [reccount] => 0 ) [3] => stdClass Object ( [reccount] => 2 ) ) 0002
You need to pass $resultq2 to the view as well.
In the controller, just before calling the view
$data['resultq2'] = $resultq2
You can now use $resultq2 in your view.
PS - SQL queries should be in models, not controllers.
Just Write '$data['resultq2'] = $resultq2' before loading the view,
$data['resultq2'] = $resultq2
$this->load->view('forumview', $data, true);
And you can retrieve it in the view by $result2 variable.
Just do var_dump($result2); in your view file, You will get the complete data of $result2 varaible.
And xbonez is right, do write your DB queries in the model, controller is only for login, and coordinating between (models, views, libraries, helper etc...)
I optimized your second query a bit, but logic is pretty much the same.
$q = $this->db->select(array(
'spf.id as id' ,
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1= $q->result_array();
$data['resultq1'] = $resultq1;
$ids = array();
foreach($resultq1 as $result)
$ids[] = $result['id'];
$resultq2 = $this->db->select("count('id') as reccount ")->from('sp_forum_topic spft')->where_in('spft.forumid',$ids)->get();
foreach( $resultq2->result_array() as $res )
$newArr[$res['forumid']] = $res;
$data['resultq2'] = $newArr;
After resultq2 is indexed by original id, its easy to use id from resultq1 loop to show correct data
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >
<?php
print_r( $resultq2[$row['id']]);
?>
</td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
This should fix it.
Modify the controller - see comments also
<?php
//Query 1
$q = $this->db->select(array(
'spf.id as id',
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1 = $q->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();
foreach ($resultq1 as $rec) {
//query 2
//echo $id = $rec['id']; //Test and See if all IDs echo out correctly
$data["id"] = $id; //Add this for the ID
$q1 = $this->db->select("count('id') as reccount, spft.forumid")->from('sp_forum_topic spft')->where('spft.forumid', $id)->get();
$resultq2[$id] = $q1->result(); //Change this line
$data["resultq2"][$id] = $resultq2[$id]; //Add this line
}
//echo "<pre>";
//$export = var_export($data, true);// Test the returned value...
//echo "</pre>";
$this->load->view('forumview', $data, true);
?>
In Your view
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php //foreach ($resultq1 as $row): ?>
<?php foreach ($data as $row): ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td>
<?php
//$resultq2 is now array
//print_r($resultq2); //Do this so you can see the depth of the array
foreach ($resultq2 as $counts) {
foreach ($counts as $count) { //The second foreach might be necessary - please test
echo $count->reccount; //This should print out the count result
//echo "<br />";
}
}
?>
</td>
<td><?php echo $row['added_by']; ?></td>
<td ><?php echo $row['added_on']; ?></td>
<td >
</td>
</tr>
<?php
endforeach;
exit;
?>
</table>
I haven't had time to test it but it should work. Let me know if you find any issues:

pass two query result to view in codeigniter

i have two query $q1 and $q2.
from the query1 i get multiple records and each record having id and i want use this id for second query in where condition.
i am doing this in controller.
i have tried following code.
In the foreach i am trying to store id and pass to $q2 where condition.
//Query 1
$q1 = $this->db->select(array(
'spf.id as id' ,
'spf.name',
'spf.added_on'
))->from('sp_form spf')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$data['data'] = $q1->result_array();
foreach($data as $rec)
{
$id = $rec['id']; // here how i catch id for each row
//Query 2
$q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')->where('spft.formid',$id)->get();
$data['count'] = $q1->row_object();
}
// pass combine result to view
$this->load->view('myview', $data,true);
Edit:
This is my view.
I have try Nishant answer and i get resultq1 using foreach but how can i get result of resultq2.
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >---- </td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
you can do it like This.
$resultq1= $q1->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();$i=0;
foreach($resultq1 as $row){
$id = $row['id'];
$q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')>where('spft.formid',$id)->get();
$resultq2[$i]['count'] = $q1->row_object();
$i++;
}
$data['resultq2'] = $resultq2;
$this->load->view('myview', $data,true);
OR
You can use array_merge
like
$data = array_merge($resultq1, $resultq2);
Then in the myview you will get both the results in variables $resultq1, and $resultq2.
You can pass any numbers of the variables from the controller to the view file by $data['variable_name'] and it can be retrieved in the view file like simple variable $variable_name.
Some Sample links which might help :-
Passing 2 types of array variables in codeigniter view files
$data['count'] = $q1->row_object();
change this like below:
foreach($data as $rec)
{
$id = $rec['id']; // here how i catch id for each row
$q2 = $this->db->select("count('id') as count ")->
from('sp_topic spft')->where('spft.formid',$id)->get();
$data[$id]['count'] = $q2->result_array();
}
$this->load->view('myview', $data,true);

Resources