Joins are not working in model [duplicate] - codeigniter

This question already has answers here:
Multiple Joins in Codeigniter
(4 answers)
Closed 7 years ago.
//model
public function getAllPurchaseItems($purchase_id)
{
$this->db->select('purchase_items.purchase_id,
purchase_items.transfer_id, purchase_items.product_id,
purchase_items.product_code, purchase_items.product_name,
purchase_items.option_id, purchase_items.net_unit_cost,
purchase_items.quantity, purchase_items.warehouse_id,
purchase_items.item_tax, purchase_items.tax, purchase_items.discount,
purchase_items.item_discount, purchase_items.expiry,
purchase_items.subtotal, purchase_items.quantity_balance,
purchase_items.date, purchase_items.status, categories.name');
$this->db->from('purchase_items');
$this->db->join(products, 'products.id = purchase_items.product_id');
$this->db->join(categories, 'categories.id = products.category_id');
$this->db->order_by('purchase_items.id', 'asc');
$q = $this->db->where(array('purchase_items.purchase_id' =>
$purchase_id));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return FALSE;
}
// controller
$this->data['rows'] = $this->purchases_model->getAllPurchaseItems($purchase_id);

Your Model Like this
$this->db->select('purchase_items.purchase_id, purchase_items.transfer_id, purchase_items.product_id, purchase_items.product_code, purchase_items.product_name, purchase_items.option_id, purchase_items.net_unit_cost, purchase_items.quantity, purchase_items.warehouse_id, purchase_items.item_tax, purchase_items.tax, purchase_items.discount, purchase_items.item_discount, purchase_items.expiry, purchase_items.subtotal, purchase_items.quantity_balance, purchase_items.date, purchase_items.status, categories.name');
$this->db->from('purchase_items');
$this->db->join('products', 'products.id = purchase_items.product_id');
$this->db->join('categories', 'categories.id = products.category_id');
$this->db->where(array('purchase_items.purchase_id' => $purchase_id));
$q = $this->db->order_by('purchase_items.id', 'asc');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result_array();
}
else
{
return false;
}

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);

Where get_active_posted_job_by_id function in ci

public function get_active_posted_job_by_id($id){
$Q = $this->db->query("CALL get_active_posted_job_by_id($id)");
if ($Q->num_rows() > 0){
$return = $Q->row();
} else {
$return = 0;
}
$Q->next_result();
$Q->free_result();
return $return;
}
Do like this
return $this->db->get_where('table_name', ['id' => $id])->row();
This will give only one record according to $id

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');
}
}

Best Practice: Models and Controllers

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();
}
}
?>

How to fix "Call to a member function getUser()" in facebook via CodeIgniter?

I am sitting in my chair for 2 hours and I cannot find what is wrong with this. I'm new to codeigniter things and I only got this error for the first time. Can you guys help me? Any help would be appreciated. Thanks in advance so much ...
****A PHP Error was encountered
Severity: Notice
Message: Undefined property: Facebook_model::$facebook
Filename: models/facebook_model.php
Line Number: 15
Fatal error: *Call to a member function getUser() on a non-object in C:\xampp\htdocs\hpbge\hpbge_files\system\hpbgestrong text_web_app\models\facebook_model.php on line 15*****
<?php
class Facebook_model extends Model {
public function get_user() {
$query = $this->facebook->getUser();
if ($query) {
$data['is_true'] = TRUE;
$data['facebook_uid'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function get_access_token() {
$query = $this->facebook->getAccessToken();
if ($query) {
$data['is_true'] = TRUE;
$data['access_token'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function get_api_secret() {
$query = $this->facebook->getApiSecret();
if ($query) {
$data['is_true'] = TRUE;
$data['api_secret'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function get_app_id() {
$query = $this->facebook->getApiSecret();
if ($query) {
$data['is_true'] = TRUE;
$data['app_id'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function get_logout_url() {
$query = $this->facebook->getLogoutUrl(array('next' => base_url()));
if ($query) {
$data['is_true'] = TRUE;
$data['logout_url'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function get_signed_request() {
$query = $this->facebook->getSignedRequest();
if ($query) {
$data['is_true'] = TRUE;
$data['signed_request'] = $query;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function set_access_token($access_token) {
$query = $this->facebook->setAccessToken($access_token);
if ($query) {
$data['is_true'] = TRUE;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function set_api_secret($app_secret) {
$query = $this->facebook->setApiSecret($app_secret);
if ($query) {
$data['is_true'] = TRUE;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
function set_app_id($app_id) {
$query = $this->facebook->setAppId($app_id);
if ($query) {
$data['is_true'] = TRUE;
return $data;
} else {
$data['is_true'] = FALSE;
return $data;
}
}
//function is formatted for the following
//https://graph.facebook.com/ID/CONNECTION_TYPE?access_token=123456
function get_facebook_object($object, $facebook_uid, $access_token) {
$fb_connect = curl_init();
curl_setopt($fb_connect, CURLOPT_URL, 'https://graph.facebook.com/'.$facebook_uid.'/'.$object.'?access_token='.$access_token);
curl_setopt($fb_connect, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($fb_connect);
curl_close($fb_connect);
$result = json_decode($output);
if (isset($result->error)) {
$data['is_true'] = FALSE;
$data['message'] = $result->error->message;
$data['type'] = $result->error->type;
$data['code'] = $result->error->code;
return $data;
} else {
$data['is_true'] = TRUE;
$data['data'] = $result->data;
return $data;
}
}
}
It seems that you have not loaded the facebook library put this line in your construct of model file
$this->load->library('facebook', array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET'
));
and make sure that you have put the facebook.php and base_facebook.php in libraries folder under application.

Resources