Home > Mobile >  Codeigniter : how can i get user data by user_id
Codeigniter : how can i get user data by user_id

Time:01-12

I'm still very new to this codeigniter. So i have a tables in my database called users table and t_lowongan table. The t_lowongan table have user_id field as a foreign key for the id_user in the users table. So when the user login and create a job posting, the user_id will be filled by the id_user from that user. I want to get the user data so that this user know which job posting that he has created by that user, but the data isn't showing, how can i fix it??

The Controller Lowongan :

public function lowongan()
    {
        $this_id = $this->session->userdata('id_user');
        $data['t_lowongan'] = $this->db->get_where('t_lowongan', ['user_id', $this_id])->result();
        $this->load-view('lowongan', $data);
    }

CodePudding user response:

Your approach to debugging isn't quite right here. Firstly, you must understand that the database object's result() method returns an array of row objects in the form of $row->field (or in your case, $row->user_id). On the other hand, the database object's result_array() method returns an array of arrays (in your case, $row['user_id']). Since you've used the former, I hope you've dealt with those row objects accordingly in the lowongan view which you then show. Failure to do so might result in the problem you've described in the question.

Assuming you've taken care of the view, the second thing to do then is to place an error_log() statement and see what value it's returning. You can place something like this just after the get_where() statement and then observe your HTTP server logs what value it's getting:

error_log("THE RESULT IS: " . print_r($data, true));

Depending on whether or not this is printing the correct value, you can then further troubleshoot where exactly the problem lies.

CodePudding user response:

You must create controller and model and call model from construct

constroller :

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class LowonganController extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model(array('m_lowongan'));
    }

    public function lowongan() {
        $id = $this->session->userdata('id_user');
        $data['t_lowongan']  = $this->m_lowongan->get_user_by_id($id);
        $this->load-view('lowongan', $data);
    }
}

model:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_Lowongan extends CI_Model {
    public function __construct()
    {
        parent::__construct();
    }
    public function get_user_by_id($id)
    {
        $this->db->where('user_id', $id);
        $query  = $this->db->get('your_table_name');
        return $query->row_array();
    }
}
  • Related