Best Practice: Models and Controllers - codeigniter

I would like to get your MVC experience on the following:
I have a table where I say which user_id is in which group_id and a second table where I say which user_id has which user_name.
Now I want a function to which I pass a group_id and it gives me all user_names in the group.
The question is, what does the Controller do and what the Model:
Controller calls a Model (get_user_ids_from_group) that returns the user ids and then the controler calls different model (get_user_name_by_id) to return the usernames.
A controller calls a Model (`get_user_names_from_group) and the model internally gets first the user ids and then the user names.
I understand that the first way is more MVC strict. But how strict would you be in a case like this? Right now I am always being very strict.
As a result my model functions have always just two lines (query and return) and my controller are bigger. So to make controller and model size more equal the second option would be possible.

Actually, it has nothing to do with MVC, as CodeIgniter doesn't implement MVC, but a sort of MVP.
However, if you're using RDBMS such as MySQL, you could JOIN these two table (within the Model) and fetch the result (within the Controller) as I suggested in a similar topic on SO.
application/models/user.php
class User extends CI_Model
{
public function get_users_by_group($group_id)
{
$this->db->select('*')->from('groups');
// While group_id and user_id have a N:1 relation
$this->db->where('group_id', $group_id);
$this->db->join('users', 'users.user_id = groups.user_id');
$query=$this->db->get();
return $query->result_array();
}
}
Then fetch and pass the result within the Controller:
application/controllers/users.php
class Users extends CI_Controller
{
public function view($group_id)
{
$this->load->model('user');
// Fetch the result from the database
$data['users'] = $this->user->get_users_by_group($group_id);
// Pass the result to the view
$this->load->view('users_view', $data);
}
}

In MVC model should not be only use for storing and getting the data but also it should contain the business logic.
Controller - Should take input communicate with model and view
Model - Should contain business logic and data store
View - Only for Output
So its like Input -> Process -> Output
Also its depend on you where to put what and you should have a balance code on controller and model, Not write everything in controller or in model
In you case I think you should uses get_user_names_from_group and just pass the group name and make a join query between two table. And when you define your function in the model its give you the option to reuse the function again in case you need same thing on next controller.

Common model example:
<?php
class Common_model extends CI_Model {
function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
if (!empty($in_data) and !empty($in_column)) {
$this->db->where_in($in_column,$in_data);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {
if (!empty($limit)) {
$offset = (empty($limit_val)) ? '0' : $limit_val;
$this->db->limit($limit, $offset);
}
if (!empty($select)) {
$this->db->select($select);
}
if ($orderby_field)
$this->db->order_by($orderby_field, $orderby_val);
if ($where_field)
$this->db->where($where_field, $where_val);
$query = $this->db->get($table);
//return $query->num_rows;
//echo $this->db->last_query();
if ($query->num_rows > 0) {
return $query->result_array();
}
}
function alldata($table) {
$query = $this->db->get($table);
return $query->result_array();
}
function alldata_count($table, $where) {
$query = $this->db->get_where($table, $where);
return $query->num_rows();
}
function insert_entry($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
function update_entry($table_name, $data, $where) {
return $this->db->update($table_name, $data, $where);
}
public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
if (!empty($select_columns)) {
$this->db->select($select_columns);
} else {
$this->db->select('*');
}
$this->db->from($table);
$this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
$this->db->where($where);
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
} else {
$this->db->limit($limit);
}
}
if (!empty($order_column)) {
$this->db->order_by($order_column, $order_by);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
if ($is_single_record) {
$rs = $query->result_array();
return $rs[0];
} else {
return $query->result_array();
}
} else {
return false;
}
}
function DeleteRecord($table_name, $where) {
return $this->db->delete($table_name, $where);
}
function managerecord() {
$count = 1;
$where = array('channel_id' => 8,
'field_id_12 !=' => '');
$this->db->where($where);
$query = $this->db->get('channel_data');
$data = $query->result_array();
foreach ($data as $value) {
$id = $value['field_id_12'];
$update = array('telephone' => $value['field_id_53'],
'about' => $value['field_id_54'],
'license' => $value['field_id_18'],
'broker' => $value['field_id_19'],
'preferred' => 'yes');
$this->db->update('members', $update, array('member_id' => $id));
}
echo "done1";
}
public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
$this->db->select($field);
$this->db->from($table);
$this->db->where($id_name, $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_field_landing_page($id = false,$fields=false) {
$this->db->select($fields);
$this->db->from('terratino_form_fields_master');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
?>

Related

Codeigniter3.x calling multiple stored procedure cache

This is somewhat related to [CodeIgniter active records' problems calling multiple stored procedures
but I am not experiencing a blank page; instead when I am passing my data array to view it seems that the the preceding array also being drag to the view.
model
public function data1($student) {
$year = 1;
$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql, array($course, $student, $year, $sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
public function data2($student) {
$year = 1;
$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
Controller:
$data['data1']=data1 from my model(SP);
$data['data2']=data2 from my model(SP);
View:
foreach($data2 as key => $value ) {
echo ....;
}
Here's the PROBLEM... in the view, I only wanted to output the $data2 but to my surprise $data1 is also being output.
Does anybody else have this issue?
I JUST SOLVE IT.
Model
public function data1($student){
**$this->db->initialize();**
$year = 1;$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
public function data2($student){
**$this->db->initialize();**
$year = 1;$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
controller
$data['data1']=data1 from my model(SP);
**$this->db->close();**
$data['data2']=data2 from my model(SP);

Codeigniter-passing value from controller to model

My English is not good so sorry for any mistake. I'm new to Codeigniter, I am trying to search record by using this code, this is my controller code:
public function search() {
if(isset($_POST['search']))
{
$s = $_POST['search'];
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
$data['user'] = null ;
if($res)
{
$data['user'] = $res ;
}
$this->load->view('filter' , $data);
}
}
It is working fine but I want to write this code in separate Model.
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
But i don't know how to pass this variable value $s = $_POST['search']; to my model. Any suggestion?
you can try the following
//in your application/models Folder put a File called UserSearch_Model.php
class UserSearch_Model extends CI_Model
{
public function search($strSearch)
{
$query = $this->db
->select('u_id,name,email,phone')
->from('user')
->where('name' ,$s)
->get();
return $query->result();
}
}
//and in your controller
public function search()
{
$strSearch = $this->input->post('search');
if (!empty($strSearch))
{
$data = [];
$this->load->model("UserSearch_Model");
$data['user'] = $this->UserSearch_Model->search($strSearch);
if (is_array($data['user']) && count($data['user']) > 0)
{
$this->load->view('filter' , $data);
}
}
}
You can try this solution for your problem :
public function search() {
$search_value = $this->input->post('search'));
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
if (isset($search_value) && !empty($search_value)) {
$this->db->where('name',$search_value);
// OR
$this->db->like('name', $search_value);
}
$query = $this->db->get();
$res = $query->result();
$data['user'] = null;
if ($res) {
$data['user'] = $res;
}
$this->load->view('filter', $data);
}
I hope it will help.
Controller
public function search() {
$search = $this->input->post('search');
$this->load->model('your_model'); //<-- You can load the model into "__construct"
$search_result = $this->your_model->your_search_function($search); //<-- This is how you can pass a variable to the model from controller
$this->load->view('your_view',['search_result'=>$search_result]); //<-- This is how you can load the data to the view. Hear your search result array is loaded on your view
}
Model
public function your_search_function($search) {
//You will receive this search variable ^^ here in your model
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name',$search);
$query = $this->db->get();
$result = $query->result_array();
if(isset($result) && !empty($result))
{
return $result;
} else
{
return FALSE;
}
}

Count with join still not displaing correct count

What I am trying to do is create a list of how many replies this thread has. I can count the number of replys fine.
But what I would like to be able to do is count the user thread also.
This is what the out put looks like. It only counts it from my replys table cannot seem to get it to count from my join as well.
Username Post
demo 2
admin 1
Should out put like
Username Post
demo 3 <-- Because the user has asked the Question / "thread" and has replied twice
admin 1
Question How to make sure it can count the user id from the join() thread table?
Model function
public function number_of_replies($user_id, $thread_id) {
$this->db->select('*');
$this->db->from('reply');
$this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
Controller
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index($thread_id = '') {
$data['users'] = array();
$data['thread_id'] = $thread_id;
$results = $this->get_users_who_replied($thread_id);
if (isset($results)) {
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'total' => $this->number_of_replies($result['user_id'], $thread_id),
);
}
}
$data['total_posts'] = '';
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
public function get_users_who_replied($thread_id) {
$this->db->select('user.username, user.user_id, reply.thread_id');
$this->db->distinct();
$this->db->from('reply');
$this->db->join('user', 'user.user_id = reply.user_id', 'left');
$this->db->join('thread', 'thread.user_id = user.user_id', 'left');
$this->db->where('reply.thread_id', $thread_id);
$this->db->order_by('thread.user_id', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
public function number_of_replies($user_id, $thread_id) {
$this->db->select('*');
$this->db->from('reply');
$this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
}
Thread Table
Reply Table
Do sum 2 tables user_id columns
public function number_of_replies($user_id, $thread_id) {
$this->db->select('t1.*, count(t2.user_id)+count(t1.user_id) AS total_posts');
$this->db->from('reply AS t1');
$this->db->join('thread AS t2', 't2.user_id = t1.user_id', 'left');
$this->db->where('t1.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
I seem to have got it working mostly now bit more testing to do
What I have had to do is create to functions for counting one for replies and one for threads
public function replies_by_users($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('reply');
}
public function thread_by_user($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('thread');
}
Then combine them and using plus + and then return it
public function total_replies_and_thread($user_id, $thread_id) {
return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
}
And then use the total_replies_and_thread($user_id, $thread_id) in the array itself like
$results = $this->get_replies($thread_id);
if ($results) {
foreach ($results as $result) {
$data['users'][] = array(
'reply_id' => $result['reply_id'],
'user_id' => $result['user_id'],
'thread_id' => $result['thread_id'],
'username' => $result['username'],
'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
);
}
}
Out put now correct
Controller HMVC
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index($user_id, $thread_id) {
$data['users'] = array();
$results = $this->get_replies($thread_id);
if ($results) {
foreach ($results as $result) {
$data['users'][] = array(
'reply_id' => $result['reply_id'],
'user_id' => $result['user_id'],
'thread_id' => $result['thread_id'],
'username' => $result['username'],
'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
);
}
}
$data['user_id'] = $user_id;
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
// Model code is just on here for testing purpose you should all ways create a model for it self.
public function get_replies($thread_id) {
$this->db->select('reply.*, user.username');
$this->db->from('reply');
$this->db->join('user', 'user.user_id = reply.user_id');
$this->db->where('thread_id', $thread_id);
$this->db->group_by('user_id');
$this->db->order_by('thread_id', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
public function total_replies_and_thread($user_id, $thread_id) {
return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
}
public function replies_by_users($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('reply');
}
public function thread_by_user($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('thread');
}
}

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

Resources