Get Username Matches ID - codeigniter

I have tried many ways of getting the username in codeigniter models. that matches the row id. But can not seem to get my model to work.
I have looked at user guide many times all ways get errors.
It shows the row id / user id OK when echo it
But can not seem to make a model to be able to match username with row id and then echo it.
Any suggestion on suitable model function.
when I click on my edit button it shows up in url http://localhost/codeigniter/codeigniter-blog/admin/users/edit/1 which works.
Model
// Not return username that matches id.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_user extends CI_Model {
function getUsername() {
$this->db->select('username');
$this->db->where('user_id');
$query = $this->db->get('user');
return $query->row();
}
}
Controller function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('user');
if ($this->session->userdata('isLogged') == TRUE) {
return true;
} else {
redirect('/');
}
}
public function index() {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['text_enabled'] = "Enabled";
$data['text_disabled'] = "Disabled";
$results = $this->model_user->getUsers();
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'edit' => site_url('users/edit/' . $result['user_id'])
);
}
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_list', $data);
}
function edit($user_id = 0, $user_group_id = 0) {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['user_id'] = "Current User ID" . " " . $user_id . ":";
$data['user_group_id'] = "Current User Group ID" . " " . $user_group_id . ":";
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}

'where' requires a second argument, which you would pass as an argument to your model function. so something like this in the model
class Model_user extends CI_Model {
function getUsername($id) {
$this->db->select('username');
$this->db->where('user_id', $id);
$query = $this->db->get('user');
return $query->row();
}
}
this corresponds to an sql query like
SELECT username FROM user WHERE user_id = ?
so in the controller just pass the user id in the argument to the model function
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername($user_id);

I have found best way to get my username to match user id
On My Model
function getUsername($user_id) {
if (empty($user_id)) {
return FALSE;
}
$this->db->select('username');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user');
if ($query->num_rows() == 1) {
$result = $query->result_array();
return $result[0]['username'];
} else {
return FALSE;
}
}
on Controller function
$this->model_user->getUsername($user_id);

Related

Codeigniter function_exists not working correctly

I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}
function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);

getting the id when the data is saved into the database using codeigniter

Hi i have this form when save, saved into the database. I want that when the data is saved into the database i will get the id on it then displaying it to the next page.
Here's my controller below in my function add_new
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_album extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->model('admin_model', 'am');
$this->load->library('form_validation');
if(!$this->session->userdata('logged_in')){
redirect('login');
}
}
public function detail($id){
return $id;
$this->data['item'] = $this->am->getItem($id);
print_r($this->data['item']);exit;
}
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$itemId);
}
}
public function index(){
$this->data['title'] = 'Create Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}
}
my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function getItem($id){
return $this->db->select('item.id,
item.parent_id,
item.title,
item.description,
item.filename
'
)
->from('item')
->where('item.id', $id)
->get()->result_object();
$this->db->get('item');
}
}
?>
Can someone help me figured this out? i want to get the ID when the data is saved. Any help is muchly appreciated. Thank you
Simply use this
$this->db->insert_id(); // Returns your row id.
Here how your controller should look like
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id()); // here?
}
}
Think you're probably looking for the insert_id() query helper function. You can see info about it in the Codeigniter docs.
When PHP hits return in a function it does just that, return a value, and it exits the function. Code following the return will not be executed. Read about it on the docs page
Example:
public function detail($id){
return $id;
echo 'here';
}
You will never get 'here' to echo, since you have already returned a value in your function().
Again this applies twice in your code, once here:
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id());
and again here:
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
If you want the insert id you are going to have to return it from $this->am->saveAlbum(); Assign that to a variable and pass it to your redirect.
There are quite a few other issues, but that should help to get you started.

model and controller error CI

In my codeigniter controller user and user model currently I am trying to get the users from my database and have them as a table format on the view page.
I am getting two errors on my model though. I am trying to use sql. Database is auto loaded.
Not to sure what done wrong
Error 1
A PHP Error was encountered
Severity: Notice
Message: Undefined property: CI_DB_mysqli_result::$rows
Filename: user/user_model.php
Line Number: 46
Error 2
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: user/user.php
Line Number: 75
My User Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function getTotalUsers() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . $this->db->dbprefix . "user`");
return $query->row('total');
}
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows; // Line 46
}
}
User Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('users');
$this->load->library('config_functions');
$this->load->model('user/user_model');
$this->load->model('user/User_group_model');
$this->lang->load('user/user', 'english');
$this->lang->load('english', 'english');
}
protected function getList() {
if (null !==($this->input->get('sort'))) {
$sort = $this->input->get('sort');
} else {
$sort = 'username';
}
if (null !==($this->input->get('order'))) {
$order = $this->input->get('order');
} else {
$order = 'ASC';
}
if (null !==($this->input->get('page'))) {
$page = $this->input->get('page');
} else {
$page = 1;
}
$url = '';
if (null !==($this->input->get('sort'))) {
$url .= '&sort=' . $this->input->get('sort');
}
if (null !==($this->input->get('order'))) {
$url .= '&order=' . $this->input->get('order');
}
if (null !==($this->input->get('page'))) {
$url .= '&page=' . $this->input->get('page');
}
$data['users'] = array();
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $this->config_functions->get('config_limit_admin'),
'limit' => $this->config_functions->get('config_limit_admin')
);
$user_total = $this->user_model->getTotalUsers();
$results = $this->user_model->getUsers($filter_data);
foreach ($results as $result) { // Line 75
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? $this->lang->line('text_enabled') : $this->lang->line('text_disabled')),
'date_added' => date($this->lang->line('date_format_short'), strtotime($result['date_added']))
);
}
$this->load->view('template/user/user_list', $data);
}
}
You may try this:
Change
return $query->rows; // Line 46
To
return $query->result_array();
$query->result() gives object notation, and $query->result_array() gives a array notation.
If you have used $query->result(), your foreach would be like:
foreach ($results as $result) { // Line 75
$data['users'][] = array(
'user_id' => $result->user_id, //the object type
...
);
}
"$query->rows()" does not exist in codeigniter active record class.
you will need to use $query->result() or $query->result_array() instead

select fails in custom model codeigniter 2

I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

Resources