how to use this recursive code in codeigniter - 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

Related

How to use Ajax pager in Drupal7

I want to use ajax_pager in my block.
I've installed Libraries API and Ajax Pager API (as it described on the AP API page). But it's still not working.
When I use 'pager' instead of 'ajax_pager' it works.
What I'm doing wrong?
<?php
function latest_news_block_info() {
$blocks['latest_news_block'] = array(
// info: The name of the block.
'info' => t('Latest News'),
);
return $blocks;
}
function latest_news_block_view($delta = '') {
// The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'latest_news_block':
// Create your block content here
$block['subject'] = t('Last news');
$query = new EntityFieldQuery();
//change news by the name of your content type
$entities = $query->entityCondition('entity_type', 'node')
->pager(5, 0)
->entityCondition('bundle', 'news')
->propertyOrderBy("created", "DESC")
->execute();
$content = "";
foreach($entities['node'] as $obj) {
$node = node_load($obj->nid);
$content .= "<img src='" .file_create_url($node->field_image['und'][0]['uri']) . "' width='200px' height='200px'>" . l($node->title, "node/" . $node->nid) . truncate_utf8($node->body['und'][0]['value'], 200, true, true) . '<br><hr>';
$block['content'] = $content;
}
break;
}
$pager = theme('ajax_pager', array('parameters' => array('selector' => 'block-system-main')));
$block['content'] .= $pager;
return $block;
}

get all Categories and SubCatgories without loading model in foreach loop

I want to display all categories and their subcategories in primary nav menu.
When i hover on cateory, it should display its subcategories.
I want to implement this functionality without loading Mage::getModel('catalog/category') in foreach loop.
as you want to write code in phtml file use below code which create tree structure of category.
<ul>
<?php
$obj = new Mage_Catalog_Block_Navigation();
$storeCategories = $obj->getStoreCategories();
Mage::registry('current_category') ? $currentCategoryId = Mage::registry('current_category')->getId() : $currentCategoryId='';
foreach ($storeCategories as $_category):
?>
<li>
<strong><?php echo $_category->getName(); ?></strong>
<?php $categoryChildren = $_category->getChildren(); ?>
<?php if($categoryChildren->count()) : ?>
<ul>
<?php foreach($categoryChildren as $_categoryChild) : ?>
<?php $_categoryChildModel = Mage::getModel('catalog/category')->load($_categoryChild->getId());?>
<?php $categoryGrandchildren=$_categoryChild->getChildren(); ?>
<li>
<?php
$currentCategoryId===$_categoryChild->getId() ? $bold="style=\"font-weight:bold\"" : $bold='';
echo ' ' . '<a href="' . $_categoryChildModel->getUrl() . '"' . $bold . '>' . $_categoryChild->getName() . '(' . $_categoryChildModel->getProductCollection()->count() . ')</a>';
?>
</li>
<?php if($categoryGrandchildren->count()) : ?>
<?php foreach($categoryGrandchildren as $_categoryGrandchild) : ?>
<?php $_categoryGrandchildModel = Mage::getModel('catalog/category')->load($_categoryGrandchild->getId());?>
<li>
<?php
$currentCategoryId===$_categoryChild->getId() ? $bold="style=\"font-weight:bold\"" : $bold='';
echo '  ' . '<a href="' . $_categoryGrandchildModel->getUrl() . '"' . $bold . '>' . $_categoryGrandchild->getName() . '(' . $_categoryGrandchildModel->getProductCount() . ')</a>';
?>
</li>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach ?>
</ul>
and using css and HTML you can achieve your goal to display sub menu on hover of main menu.
Still let me if you need any other help.
Thanks
ok so I just did this and I figured I'd search to see if anyone was wondering how to achieve this. The trick to this is
Mage::getResourceSingleton('catalog/category')->getAttributeRawValue($categoryEntityId,array('name','level','url_key','path','is_active'),Mage::app()->getStore());
This does not load the category model lets take a look at what it is actually doing.
Go to app/code/core/Mage/Catalog/Model/Resource/Abstract
public function getAttributeRawValue($entityId, $attribute, $store)
{
if (!$entityId || empty($attribute)) {
return false;
}
if (!is_array($attribute)) {
$attribute = array($attribute);
}
$attributesData = array();
$staticAttributes = array();
$typedAttributes = array();
$staticTable = null;
$adapter = $this->_getReadAdapter();
foreach ($attribute as $_attribute) {
/* #var $attribute Mage_Catalog_Model_Entity_Attribute */
$_attribute = $this->getAttribute($_attribute);
if (!$_attribute) {
continue;
}
$attributeCode = $_attribute->getAttributeCode();
$attrTable = $_attribute->getBackend()->getTable();
$isStatic = $_attribute->getBackend()->isStatic();
if ($isStatic) {
$staticAttributes[] = $attributeCode;
$staticTable = $attrTable;
} else {
/**
* That structure needed to avoid farther sql joins for getting attribute's code by id
*/
$typedAttributes[$attrTable][$_attribute->getId()] = $attributeCode;
}
}
/**
* Collecting static attributes
*/
if ($staticAttributes) {
$select = $adapter->select()->from($staticTable, $staticAttributes)
->where($this->getEntityIdField() . ' = :entity_id');
$attributesData = $adapter->fetchRow($select, array('entity_id' => $entityId));
}
/**
* Collecting typed attributes, performing separate SQL query for each attribute type table
*/
if ($store instanceof Mage_Core_Model_Store) {
$store = $store->getId();
}
$store = (int)$store;
if ($typedAttributes) {
foreach ($typedAttributes as $table => $_attributes) {
$select = $adapter->select()
->from(array('default_value' => $table), array('attribute_id'))
->where('default_value.attribute_id IN (?)', array_keys($_attributes))
->where('default_value.entity_type_id = :entity_type_id')
->where('default_value.entity_id = :entity_id')
->where('default_value.store_id = ?', 0);
$bind = array(
'entity_type_id' => $this->getTypeId(),
'entity_id' => $entityId,
);
if ($store != $this->getDefaultStoreId()) {
$valueExpr = $adapter->getCheckSql('store_value.value IS NULL',
'default_value.value', 'store_value.value');
$joinCondition = array(
$adapter->quoteInto('store_value.attribute_id IN (?)', array_keys($_attributes)),
'store_value.entity_type_id = :entity_type_id',
'store_value.entity_id = :entity_id',
'store_value.store_id = :store_id',
);
$select->joinLeft(
array('store_value' => $table),
implode(' AND ', $joinCondition),
array('attr_value' => $valueExpr)
);
$bind['store_id'] = $store;
} else {
$select->columns(array('attr_value' => 'value'), 'default_value');
}
$result = $adapter->fetchPairs($select, $bind);
foreach ($result as $attrId => $value) {
$attrCode = $typedAttributes[$table][$attrId];
$attributesData[$attrCode] = $value;
}
}
}
if (sizeof($attributesData) == 1) {
$_data = each($attributesData);
$attributesData = $_data[1];
}
return $attributesData ? $attributesData : false;
}
As you can see no model loading happening just retrieving specific pieces of info. Also being part of the resource abstract means all catalog resource models (I haven't checked other resource models but, I wouldn't be too surprised to find this in others) have this available.
If you use this in an override of Mage_Catalog_Block_Navigation you can then call all of the info you need about any category without loading the model. To traverse the tree however, you have to do terrible things.
You can use 'path'(explode on /) to easily retrieve parents but you will need to get dirty in order to retrieve children categories so something like this to get Children.
$childrenQuery = "SELECT entity_id FROM catalog_category_entity WHERE path REGEXP '^.*\/" . $categoryId . "\/[[:digit:]]?[[:digit:]]?[[:digit:]]?[[:digit:]]?$'";
$resource = Mage::getSingleton('core/resource');
$readCxn = $resource->getConnection('core/read');
$children = $readCxn->fetchAll($childrenQuery);
if ($children[0]) {
return $children;
} else {
return;
}
The overall difficulty is that all model and resource model functions will expect an instance of a category object to make them all work with just the entity_id is definitely possible just a pain.
So I would not recommend doing this in general the only reason I did this is because the default magento root category in my case was not the actual functional root of categories (fun eh). If you are using a standard root category I would recommend using the Helper functions and retrieving the info from cache.
Either way from here all you have to do complete your functions in Mage_Catalog_Block_Navigation and assemble your menu in a template. And there you go; complete category menu without ever accessing a model->load.
Try This Code
<?php
require_once("app/Mage.php");
Mage::app();
function getChildCategories($category, $First = false) {
$sub = $First ? $category : $category->getChildren();
foreach ($sub as $child) {
$_categories[] = [ "name" => $child->getName(), "id" => $child->getId(), "children" => getChildCategories($child) ];
}
return $_categories;
};
function CategoriesTree($category, $First = false) {
$sub = $First ? $category : $category->getChildren();
echo "<pre>";
foreach ($sub as $child) {
echo $child->getName(); ;
CategoriesTree($child);
}
}
$_categories = Mage::helper('catalog/category')->getStoreCategories();
$categories = getChildCategories($_categories, true);
CategoriesTree($_categories, true);
?>

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

Second join Codeigniter

My function in model looks like:
public function join($table, $select, $join, $on, $join2 = FALSE, $on2 = FALSE, $where = FALSE, $single = FALSE, $order = FALSE, $sort = FALSE, $limit = FALSE)
{
$this->db->select($select);
$this->db->from($table);
$this->db->join($join, $on);
if($join2 == TRUE)
{
$this->db->join($join2, $on2);
}
if($where == TRUE)
{
$this->db->where($where);
}
if($order == TRUE)
{
$this->db->order_by($order, $sort);
}
if($limit == TRUE)
{
$this->db->limit($limit, 0);
}
if($single == TRUE)
{
return $query->row();
}
$query = $this->db->get();
return $query->result();
}
My controller:
public function index()
{
$data['users'] = $this->users_m->get('users');
$join = "blog_list";
$on = "blog_list.id_p = users.id";
$join2 = "meeting_list";
$on2 = "meeting_list.id_p = users.id";
$data['join'] = $this->users_m->join('users', 'users.id, users.nickname, blog_list.cat2, meeting_list.id_m', $join, $on, $join2, $on2, FALSE, FALSE, 'nickname', 'desc');
$this->load->view('admin/users/index', $data);
}
And view:
<?php foreach($join as $row): ?>
<?php echo ($row->id); ?>
<?php echo ($row->nickname); ?>
<?php echo ($row->cat2); ?>
<?php echo ($row->id_m); ?>
<br>
And problem is with second join (when i use $join2), it means when i echo $row->id the id comes from table in $join2 instead from $table. When i use onle one join everything works when i specify in $select that id is from 'user'(users.id) but with second join it wont works. Any idea?
Try editting your select in this way that you select fields by name and then assign them to another name. So, par example:
public function index()
{
//Other code
$data['join'] = $this->users_m->join('users', 'users.id as uid, users.nickname, blog_list.cat2, meeting_list.id_m', $join, $on, $join2, $on2, FALSE, FALSE, 'nickname', 'desc');
//Other code
}
Now echo :
<?php echo ($row->uid); ?>

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

Resources