Codeigniter Join Not Displaying Group By Correct - codeigniter

I have this model function below which lets me join both tables. Printed results are at bottom of question.
<?php
class Forum_model extends CI_Model {
public function get_forums() {
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc', 'left');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
}
How ever when I go to look at in on my view it displays it like image below
The two General categories news, lounge should be displayed on the one panel. For some reason it displays the two general categories in own panel.
Question: How is it possiable to display the two categories together? I have tried $this->db->group_by('fc.category_forum_id')
Image
Controller
<?php
class Home extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('reports/thread_analytics_model');
$this->load->model('forum/forum_model');
}
public function index() {
$results = $this->forum_model->get_forums();
echo "<pre>";
print_r($results);
echo "</pre>";
$data['forums'] = array();
foreach ($results as $result) {
$data['forums'][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
$data['content'] = 'common/home_view';
$this->load->view('theme/default/template_view', $data);
}
}
View
<?php foreach ($forums as $forum) {?>
<div class="panel panel-home">
<div class="panel-heading"><h1 class="panel-title"><?php echo $forum['forum_name'];?></h1></div>
<div class="panel-body">
<table class="table">
<tbody>
<tr>
<td><?php echo $forum['category_name'];?></td>
</tr>
</tbody>
</table>
</div>
</div><!-- Panel -->
<?php }?>
Printed Results Image

A possible solution with your approach would be:
class Forum_model extends CI_Model {
public function get_forums() {
$arrGroupedData = array();
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach($query->result_array() AS $arrCategory)
{
$arrGroupedData[$arrCategory['forum_id']][] = $arrCategory;
}
return $arrGroupedData;
} else {
return false;
}
}
}
But in my opinion - you should probably split up your queries
1 query to get the forums and 1 query to get all categories from your forums
and stick it together in a tree structure

example for you
$forums = array();
$results = array(
array(
'forum_name' => 'general',
'category_name' => 'news1'
),
array(
'forum_name' => 'general',
'category_name' => 'news2'
),
array(
'forum_name' => 'latter',
'category_name' => 'news3'
),
);
foreach ($results as $result)
{
if(in_array($result['forum_name'],$forums))
{
$array = array($result['category_name']);
array_push($forums[$result['forum_name']],$array);
}
else
{
$forums[$result['forum_name']][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
}
echo '<pre>';
print_r($forums);

Related

Codeigniter-login with session

i am trying to do a login with sessions but it doesn't seem to be working because when i log in the session data on the view is not being displayed. once logged in it should read something like: 'Welcome Jon' but it doesn't. What could be the issue
controller fn
function login_user()
{
if(isset($_POST['login']))
{
$data = $this->Model_students->fetchUserData();
if(!empty($data))
{
var_dump($data);
foreach ($data as $key => $value) :
$user_id = $value->id;
$firstname = $value->firstname;
$lastname = $value->lastname;
$grade = $value->grade;
$email = $value->email;
$images = json_decode($value->userfile);
endforeach;
$user_info = array(
'id' => $user_id,
'firstname' => $firstname,
'lastname' => $lastname,
'grade' => $grade,
'email' => $email,
'images' => $images[0]->file_name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($user_info);
redirect('Students/homepage');
}
else
{
$this->session->set_flashdata('error', 'Error! Invalid username or password');
redirect('Students/login_user');
}
}
else
{
$this->load->view('signup');
}
}
model
the join here is for a different table in the same db where the common row is id..not sure if the join is correct too
public function fetchUserData()
{
$this->db->select('users.*, user_images.*');
$this->db->from('users');
$this->db->join('user_images', 'users.id=user_images.user', 'inner');
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get();
if($query->num_rows() == 1 ) :
foreach($query->result() as $row):
$data[] = $row;
endforeach;
return $data;
endif;
}
view the img scr here should display the user image based on what is saved on the db when he/she first registered
</head>
<body>
<h3>Welcome <?php $this->session->userdata('$firstname')?>.</h3>;
<img class ="img-circle" src="<?=base_url();?>uploads/users/<?=$this->session->userdata('userfile/file_name');?>" width="250" height="auto">
There's a typo in your views. where the session variable should be without the $ symbol.
<h3>Welcome <?php echo $this->session->userdata('firstname'); ?>.</h3>;
Also, check if the $user_info contains the expected data. Do a var_dump($user_info) and see just before creating the session.
there could be many issues with it.
1: your are passing a variable in the string which is not valid ( $this->session->userdata('$firstname') ) remove the $ from the first name;
2: there has to be a constructor in the controller so that the session could be called when ever the object is created;
hope it will solve your problem

Object of class error in Codeigniter with loading function in array

On my Welcome controller I have a function called content_top which loads function $this->$part[0]($setting_info); in this case $this->slideshow($setting_info); Then it should display that slideshow functions view in that data array.
When I have refreshed my page I get a error
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/content_top.php
Line Number: 7
Backtrace:
File: C:\wamp\www\cms\application\views\common\content_top.php
Line: 7
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 51
Function: view
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 19
Function: content_top
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
And
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/welcome_message.php
Line Number: 3
Backtrace:
File: C:\wamp\www\cms\application\views\common\welcome_message.php
Line: 3
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 20
Function: view
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
Question Is there any way to when I have a function in array to be able to make it display the view with out throwing error.
<?php
class Welcome extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->load->view('common/header');
$data['content_top'] = $this->content_top();
$this->load->view('common/welcome_message', $data);
$this->load->view('common/footer');
}
public function content_top() {
if ($this->uri->segment(1)) {
$route = $this->uri->segment(1) .'/'. $this->uri->segment(2);
} else {
$route = 'common/home';
}
$layout_id = $this->model_layout->get_layout($route);
$data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
if (isset($part[1])) {
$setting_info = $this->model_module->get_module($part[1]);
if ($setting_info) {
$data['modules'][] = $this->$part[0]($setting_info);
}
}
}
return $this->load->view('common/content_top', $data);
}
public function slideshow($setting_info) {
static $module = 0;
$data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$data['module'] = $module++;
$data['resize_errors'] = $this->image_lib->display_errors();
return $this->load->view('module/slideshow', $data);
}
}
In the CI when you loading the view and printing as a string then need to pass the third parameter as 'TRUE'.
<?php echo $this->load->view('headers/menu', '', TRUE);?>
Solved
On the controller I had to change a couple things around
I also have had to use a template layout to minimize the views
But on content_top and sideshow function I had to use return and true
return $this->load->view('folder/name', $this->data, TRUE);
Controller
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->data['title'] = 'Home';
$this->data = array(
'column_left' => $this->column_left(),
'column_right' => $this->column_right(),
'content_bottom' => $this->content_bottom(),
'content_top' => $this->content_top(),
'page' => 'common/home'
);
$this->load->view('common/template', $this->data);
}
public function column_left() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_left');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_left', $this->data, TRUE);
}
public function column_right() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_right');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_right', $this->data, TRUE);
}
public function content_bottom() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_bottom');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_bottom', $this->data, TRUE);
}
public function content_top() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_top', $this->data, TRUE);
}
/*
Add function for modules that are enabled for this page
*/
public function slideshow($setting_info) {
static $module = 0;
$this->data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$this->data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$this->data['module'] = $module++;
return $this->load->view('module/slideshow', $this->data, TRUE);
}
}
Template View
<?php $this->load->view('common/header');?>
<?php $this->load->view($page);?>
<?php $this->load->view('common/footer');?>
Content Top View
<?php foreach ($modules as $module) {?>
<?php echo $module['module_name'];?>
<?php }?>
Home View
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php echo $content_top;?>
</div>
</div>
</div>
Proof Working
This happened to me when I did this:
$model = $this->load->model('user_model);
$data = [
'model' => $model
];
instead of this:
$this->load->model('user_model);
$model = $this->user_model->edit();
$data = [
'model' => $model
];
then when I echoed out the $model, it gave me the error. So I tried to print_r then it gave me a very long array until I realize my mistake. Hope it helps.
Just remove the echo on view page when you are using CI new versions.
<?php $this->load->view('headers/menu');?>
https://stackoverflow.com/a/40675633/2790502

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

Codeigniter dropdown only retrieve last data from db

I use CI form with form_dropdown helper and tried to pull Mysql data into its options, from the below code, its only retrieve the last record from db into the option list?
please advise what is wrong with my code?
Model
public function getStates() {
$query = $this->db->get('states');
$return = array();
if($query->num_rows() > 0){
$return[''] = 'please select';
foreach($query->result_array() as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}
Controller
$this->load->model('db_model');
$data['options'] = $this->db_model->getStates();
$this->load->view('create_new', $data);
View
$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);
<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>
send full query result from the model to the view like this
Model
public function getStates() {
$query = $this->db->get('states');
return $query->result();
}
let the controller as it is and now you can populate states in dropdown like this:
View
<?php
foreach($options as $opt){
$options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?>
Try this:
function getStates() {
$return = array();
$query = $this->db->get('states')->result_array();
if( is_array( $query ) && count( $query ) > 0 ){
$return[''] = 'please select';
foreach($query as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}

codeigniter view, add, update and delete

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

Resources