model and controller error CI - codeigniter

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

Related

how to use this recursive code in codeigniter

db_connection.php
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '');
define('_DATABASE_NAME', 'test_database');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
$_GLOBAL['dbConnection'] = $dbConnection;
?>
function.php
<?php
function categoryParentChildTree($parent = 0, $spacing = '', $category_tree_array = '') {
global $dbConnection;
$parent = $dbConnection->real_escape_string($parent);
if (!is_array($category_tree_array))
$category_tree_array = array();
$sqlCategory = "SELECT id,name,parent_id FROM tbl_categories WHERE parent_id = $parent ORDER BY id ASC";
$resCategory=$dbConnection->query($sqlCategory);
if ($resCategory->num_rows > 0) {
while($rowCategories = $resCategory->fetch_assoc()) {
$category_tree_array[] = array("id" => $rowCategories['id'], "name" => $spacing . $rowCategories['name']);
$category_tree_array = categoryParentChildTree($rowCategories['id'], ' '.$spacing . '- ', $category_tree_array);
}
}
return $category_tree_array;
}
?>
index.php
<?php
require_once 'db_connection.php';
require_once 'functions.php';
$categoryList = categoryParentChildTree();
foreach($categoryList as $key => $value){
echo $value['name'].'<br>';
}
?>
can anyone help me to translating this so i can use on codeigniter? recursive function
sorry im new on codeigniter
please help

Severity Notice: Undefined offset

With some changes I got the error, This work fine in raw php but in codeigniter I'm trying to get this result_array in a while(list), but I don't know what would be the alternative for fetch_row in codeigniter. Please help me to get this in a way at while (list($d, $sn, $s) = each($IDS-)) line.
Model:
public function raw_attendance_Data() {
$this->db->select('attnDate, TraineeID, Status');
$this->db->from('tbl_attendance');
$this->db->order_by('TraineeID');
$query = $this->db->get();
return $query->result_array();
}
Controller:
public function rawAttendance(){
$data['IDS'] = $this->AttendanceModel->raw_attendance_Data();
$this->load->view('attendance/rawAttendance', $data);
}
View:
$curname='';
$tdata = '';
reset($IDS);
while (list($d, $sn, $s) = each($IDS)) {
if ($curname != $sn) {
if ($curname) {
$tdata .= "<tr><td>$curname</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
}
$rowdata = $emptyRow;
$curname = $sn;
}
$rowdata[$d] = $s;
}
$tdata .= "<tr><td>$curname</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
$query->result_array(); returns an array and not an object. Thus the $IDS in $IDS->fetch_row() is an array (a non-object).
I don't understand, where you are getting the function fetch_row()?
If I understand what you are trying to accomplish then this should work.
View:
$tdata = '';
foreach($IDS as $row)
{
$curname = isset($row['TraineeID']) ? $row['TraineeID'] : "";
$date = isset($row['attnDate']) ? $row['attnDate'] : "";
$status = isset($row['Status']) ? $row['Status'] : "";
if(!empty($curname){
$tdata .= "<tr><td>$curname</td><td>$date</td><td>$status</td></tr>";
}
}

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

Get Username Matches ID

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

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.

Resources