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

<?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

Related

codeigniter 3.1.3 pagination shows same record

i don't understand why this is happening but same row on every page reload shows. I'm new to codeigniter and know basics of php and programming. Thank you for help in advance.
model:
class Clanovi_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_clanovi($limit, $offset) {
$this->db->limit($limit, $offset);
$query = $this->db->get('clan');
return $query->result();
}
public function broji_clanove() {
return $this->db->count_all('clan');
}
}
controller:
class Clanovi extends CI_Controller {
public function index() {
$this->load->model('Clanovi_model');
$this->load->library('pagination');
$this->load->helper('url');
$config['base_url'] = 'http://localhost/codeigniter5/index.php/clanovi';
$config['total_rows'] = $this->Clanovi_model->broji_clanove();
$config['per_page'] = 1;
$this->pagination->initialize($config);
$data['clanovi'] = $this->Clanovi_model->get_clanovi($config['per_page'], $this->uri->segment(3));
$data['paginacija'] = $this->pagination->create_links();
$this->load->view('zaglavlje');
$this->load->view('clanovi', $data);
$this->load->view('podnozje');
}
}
view:
<h2>Članovi</h2>
<hr>
<table class="table table-striped">
<tr>
<th>Ime</th>
<th>Prezime</th>
<th>Adresa</th>
<th>Korisničko ime</th>
<th>Lozinka</th>
</tr>
<?php foreach ($clanovi as $clan): ?>
<tr>
<td><?php echo $clan->ime; ?></td>
<td><?php echo $clan->prezime; ?></td>
<td><?php echo $clan->adresa; ?></td>
<td><?php echo $clan->korisnicko_ime; ?></td>
<td><?php echo $clan->lozinka; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $paginacija; ?>
routes:
$route['clanovi/(:num)'] = 'clanovi/index/$1';
$route['clanovi'] = 'clanovi';
screenshot1
screenshot2
Found solution by looking what $this->uri->segment(3); does, and changed value to 2.
$data['clanovi'] = $this->Clanovi_model->get_clanovi($config['per_page'], $this->uri->segment(2));

upload image from rest client (android) to database with codeigniter

i want to upload the image profile and the user id from my android application to database. i tried this method and it work in local but when i test it with (POSTMAN) a rest client it doesn't work. i think because i call a view.
this is my code please help me.
my controller
class Users extends REST_Controller {
function __construct()
{ parent::__construct();
$this->load->model('Users_model','',TRUE);}public function index_get()
{
$this->load->view('users');
}
public function save_image_post()
{
$id = $_POST["id"];
$url = $this->do_upload();
$this->Users_model->save_image($id, $url);
//$this->Users_model->save_image($url);
}
private function do_upload()
{
$type = explode('.', $_FILES["pic"]["name"]);
$type = strtolower($type[count($type)-1]);
$url = "./images/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg", "jpeg", "gif", "png")))
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
if(move_uploaded_file($_FILES["pic"]["tmp_name"],$url))
return $url;
return "";
}
}
this is my model:
public function save_image($id,$url)
{
$this->db->set('id', $id);
$this->db->set('image_user', $url);
$this->db->insert('users');
}
this is my view:
<!DOCTYPE html><html lang="en"><head></head><body>
<?php echo form_open_multipart('api/users/save_image/'); ?>
<table class="table">
<tr>
<td>Id</td>
<td><?php echo form_input('id'); ?></td>
</tr>
<tr>
<td>Image</td>
<td><?php echo form_upload('pic'); ?></td>
</tr>
<tr><td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table></body></html>

A PHP Error was encountered Severity: Notice Message: Undefined property: Site::$site_model

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Site::$site_model
Filename: controllers/site.php
Line Number: 13
Site Controller site.php
Fatal error: Call to a member function delete_row() on a non-object in
C:\xampp\htdocs\login\application\controllers\site.php on line 13
My controller->Site.php
<?php
class Site extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
}
function delete(){
$this->site_model->delete_row();
$this->index();
}
function members_area(){
$this->load->model('patient_model');
$data['records'] = $this->patient_model->getAll();
$this->load->view('members_area', $data);
}
function add(){
$data['main_content'] = 'patient_form';
$this->load->view('includes/template',$data);
}
function is_logged_in(){
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true){
echo 'Your don\'t have permission to access this page. Login';
die();
}
}
}
My model -> site_model.php
class Site_model extends CI_Model{
function get_records(){
$query = $this->db->get('patient');
return $query->result();
}
function delete_row(){
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('patient');
}
function create_member(){
$new_member_insert_data = array(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'contact' => $this->input->post('contact'),
'remarks' => $this->input->post('remarks')
);
$insert = $this->db->insert('patient', $new_member_insert_data);
return $insert;
}
}
My view-> members_area.php
<?php $this->load->view('includes/header');?>
<div id="main">
Welcome Back, <u><?php echo $this->session->userdata('username'); ?>!</u>
<h3>Vision Eye Medical Center Patient Information</h3>
<div id="overflow">
<table class="features-table">
<thead>
<tr>
<td>Patient Name</td>
<td>Email</td>
<td>Address</td>
<td>Contact</td>
<td>Remarks</td>
<td>Action</td>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
</tfoot>
<tbody>
<?php foreach($records as $row): ?>
<tr>
<td><?php echo $row->fname;?>
<?php echo $row->lname;?>
</td>
<td><?php echo $row->email;?></td>
<td><?php echo $row->address;?></td>
<td><?php echo $row->contact;?></td>
<td><?php echo $row->remarks;?></td>
<td>View|<?php echo anchor("site/delete/$row->id",'delete');?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php echo form_open();?>
<?php echo anchor('patient/add', 'Add new Data'); ?><?php echo anchor('login/logout', 'Logout'); ?><br>
<?php echo form_close();?>
</div>
<?php $this->load->view('includes/footer');?>
It seems you are not loading your "site model" anywhere in code you can do following:
autoload it in autoload file.
load your model either in constructor of controller, or load it whenever needed by using this line $this->load->model('site_model');
More information can be found here.
You need to load model in your controller.
class Site extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
$this->load->model('site_model'); //Load site_model
........
In somecase it happens when you don't extract your form data to the model. Try extract($_POST) in your model and don't forget to load the model properly.
P.s.:this was the solution for my error

Codeigniter Get Nested Hierarchical Data from Database

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>

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:

Resources