I need to get the the subcategories of its categories in codeigniter.
I am stuck at passing category id to the my model method
my code is below :
this is my view : index.php
<ul class="list-inline">
<?php
if($category->num_rows() > 0)
{
foreach ($category->result() as $row)
{
?>
<li><img class="img-responsive center-block" width="80px" src="<?php echo base_url(); ?>assets/admin/uploads/category/<?php echo $row->cat_home_image; ?>" alt="icon" title="icon" class="img-responsive" /><p style="font-size:16px;"><?php echo $row->category_description; ?> </p></li>
<?php
}
}
?>
</ul>
this is my controller : Main.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->load->model("category_model");
$data["category"] = $this->category_model->fetch_category();
$this->load->model("ads_model");
$data["ads"] = $this->ads_model->fetch_home_ads();
$this->load->view('index',$data);
//$this->load->view('category');
}
public function getsubcategory()
{
$this->load->model("category_model");
$data["subcategory"] = $this->category_model->fetch_subcategory();
$this->load->view('category',$data);
}
}
this is my Model : category_model.php
<?php
class Category_model extends CI_Model
{
function fetch_category()
{
$query = $this->db->query("SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id IS NULL && lang_id='1' && c.id!='4' ORDER BY category_description");
return $query;
}
function fetch_subcategory()
{
$subcat = $this->db->query("SELECT * FROM category AS c INNER JOIN category_language AS cl ON c.id=cl.category_id where parent_id='1' && lang_id='1' ORDER BY category_description");
return $subcat;
}
}
?>
How to pass the category id to model to get the appropriate subcatory of category_id
Hope this will help you :
Your view should be like this :
<ul class="list-inline">
<?php
if($category->num_rows() > 0)
{
foreach ($category->result() as $row)
{?>
<li>
<a href="<?=site_url('main/getsubcategory/'.$row->id);?>">
<img class="img-responsive center-block" width="80px" src="<?=site_url('assets/admin/uploads/category/'.$row->cat_home_image); ?>" alt="icon" title="icon" class="img-responsive" />
<p style="font-size:16px;"><?php echo $row->category_description; ?> </p>
</a>
</li>
<?php
}
}
?>
</ul>
Your controller's getsubcategory method should be like this :
public function getsubcategory($id)
{
if ($id)
{
$this->load->model("category_model");
$data["subcategory"] = $this->category_model->fetch_subcategory($id);
$this->load->view('category',$data);
}
}
Your model method fetch_subcategory should be like this :
Note : make sure all column name belongs to correct table alias
function fetch_subcategory($id)
{
$this->db->select('*');
$this->db->from('category c');
$this->db->join('category_language cl', 'cl.category_id = c.id');
/* Use $id here like this
$this->db->where('parent_id', $id);
*/
$this->db->where('c.parent_id', '1');
$this->db->where('cl.lang_id', '1');
$this->db->order_by('c.category_description', 'DESC');
$result = $this->db->get()->result();
return $result;
}
Related
I have been trying to echo user information on a product but its not working. I used to try it with this join function in my model :
public function getdata()
{
$this->db->select('*');
$this->db->from('users');
$this->db->join('products','products.user_id = users.user_id');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
}
It didn't work properly because it echoed for example all the usernames from the database when I tried to echo a username that belongs to the same user_id.
Now I tried to do it like this:
This is my Controller function (AlleCadeausController):
public function index()
{
/** Laad de models **/
$this->load->model('Product_model');
$selectProducts = $this->Product_model->selectProducts();
foreach ($selectProducts as $key => $product)
{
# first name
$user = $this->Product_model->get_user_name($product['user_id']);
#append both NEW VALUES to same array
$data[$key]['voornaam'] = $user[0]['voornaam'];
}
/** Make $data **/
$data['products'] = $this->Product_model->selectProducts();
/** Laad de allecadeaus view en geef $data mee **/
$this->load->view('allecadeaus', $data);
}
My model functions in my Prduct_model.php file:
public function selectProducts()
{
$query= $this->db->query("SELECT * FROM products");
$result = $query->result_array();
return $result;
}
function get_user_name($name)
{
$query= $this->db->query("SELECT voornaam FROM users WHERE user_id = $name ");
$result = $query->result_array();
return $result;
}
And this is how I tried to echo the user information in the product foreach loop in the view:
<?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
<div class="main-products">
<img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
<div class="product_naam"><?php echo $product["product_naam"]; ?></div>
<div class="ophaal_plaats"><?php echo $product["ophaal_plaats"]; ?></div>
</div>
</a>
<div class="aangeboden_door">
<p>
<tr>
<a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
<td><?php echo $product['voornaam'];?></td>
</tr>
</p>
</div>
<?php endforeach; ?>
at this line :
<td><?php echo $product['voornaam'];?></td>I try to echo the first
name of the user of the product but its not working.
The PHP error that I'm receiving is: undefined index: voornaam , line: 55 which is this line: <td><?php echo
$product['voornaam'];?></td>
Database information of both tables products and users:
Table 1 : products:
product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id
table 2 : users:
user_id
email
voornaam
achternaam
beschrijving
profiel_foto
You can use the active records instead of create multiple function:
Your controller:
public function index()
{
$data = array();
$this->load->model('product_model');
$data['products'] = $this->product_model->selectProducts();
$this->load->view('allecadeaus', $data);
}
Your view:
Your view:
<?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
<div class="main-products">
<img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
<div class="product_naam"><?php echo $product["product_naam"]; ?></div>
<div class="ophaal_plaats"><?php echo $product["ophaal_plaats"]; ?></div>
</div>
</a>
<div class="aangeboden_door">
<p>
<tr>
<?php
//Here is the active record query which is getting the 'voorname' and other data
$userarray = $this->db->get_where('users', array('user_id'=>$product["user_id"]))->row_array();
// you can print_r($userarray); for see the array you get
?>
<a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
<td><?php echo $userarray['voornaam'];?></td>
</tr>
</p>
</div>
<?php endforeach; ?>
I'm trying to make a function in the CodeIgniter framework so users can click on product detail page, and see which user uploaded that certain product and they must be able to click on the product owner to go to his profile page.
Now, I am already able to echo owner information of the product owner on the details page. But the link to the owner profile page is not working some reason and the name isn't echoed anymore since I tried to make it a link.
This is my product details page (details.php) foreach loop function where I'm trying to echo the username of the owner of a product and link it to their profile page:
<?php include_once ('templates/header.php'); ?>
<div class="container">
<h3>Email van de eigenaar:</h4>
<?php
foreach($userdetail_list as $row)
{
?>
<tr>
<td><?php echo $row['email'];?></td>
</tr>
<?php } ?>
</div>
<div class="container">
<div class="row">
<div class="col-md-4" style="margin-top:24px;">
<img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" class="img-responsive">
</div>
<div class="col-md-5">
<h1> <div class="product_naam"> <?php echo $product['product_naam']; ?> </div> </h1>
<h3>Over dit cadeau</h3>
<div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-default">Cadeau aanvragen</button>
<div class="aangeboden_door"> Aangeboden door: <?php
foreach($userdetail_list as $row)
{
?>
<tr>
<td><?=$row['username']; ?></td>
<td><?php echo $row['email'];?></td>
</tr>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="container">
<footer>
<p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
When I load the view page I do not see the username and no link to the users profile.
Here is my controller (User.php):
<?php
class User extends CI_Controller
{
public function index()
{
$this->load->view('profile', $data);
}
public function __construct()
{
parent::__construct();
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
}
public function userdetails($user_id)
{
//load the User_model
$this->load->model('User_model');
//call function getdata in de Product_model
$data['userdata_list'] = $this->User_model->getdata();
//get product details
$data['user'] = $this->User_model->get_user_info($user_id);
//laad view
$data['main_content'] = 'profiel_user';
$this->load->view('profiel_user',$data);
}
public function profile()
{
$this->load->model('User_model');
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
$this->load->view('profile');
}
}
full model file (User_model.php)
<?php
class User_model extends CI_Model {
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function getUserInfo($user_id)
{
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$user_id.')');
return false;
}
}
public function getdata()
{
$this->db->where('user_id', $id);
$this->db->from('users');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
}
}
?>
Problably because of this line:
<?=$row['username']; ?>
Maybe your server does not support short hand tags?
try this:
<?php echo $row['username']; ?>
You also missed a semicolon here at the end:
echo base_url() . 'User/profiel_user?id='.$row['user_id']
and also here:
<a href="<?php echo base_url() ?>/Cadeauaanvragen">
You also use table row and table data tags without a surrounding table tag. Or remove all tr and td tags.
See: How do browsers analyze <tr> <td> without <table>?
I made a category menu bar on my website so you can click on a category and see products of that category, but its not working for me and I must be doing something wrong.
Some database information:
categories table:
Row 1: id
Row 2: name
In the products table:
Row: category_id
I used a db helper (db_helper.php)
<?php if (!function_exists('get_categories_h')) {
function get_categories_h(){
$CI = get_instance();
$categories = $CI->Product_model->get_categories();
return $categories;
} } ?>
This is the my Product_model file where I made the get_categories function:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product_model extends CI_model {
public function saveProduct($data) {
$this->db->insert('products', $data);
$product_id = $this->db->insert_id();
return $product_id;
}
public function get_product_details($product_id) {
$arrReturn = array();
$this->db->select('*');
$this->db->from('products');
$this->db->where('product_id', $product_id);
$query = $this->db->get();
$result = $query->result_array();
if (!empty($result)) {
$arrReturn = $result[0];
}
return $arrReturn;
}
/*
Get categories
*/
public function get_categories(){
$this->db->select('*');
$this->db->from('categories');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
}
?>
And this is the menu bar in my view file where I'm loading all my categories.
<div class="container-fluid">
<div class="row">
<div class="col-lg-1">
<div id="categorymenu">
<center> <h3>Categorieën</h3> </center>
<ul class="list-group">
<?php foreach (get_categories_h() as $category) : ?>
<li class="list-group-item">
<a href="<?php echo $category->id; ?>"><?php echo $category['name']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
</div>
I am able to echo all the categories from my database but the links are not working.
I hope someone can help me,
Thanks!
Looks like you are creating a nonsense URL for the href value. Unless the 'id' field of the 'categories' table contains values that use a "controller/method/id" scheme the links you are creating don't go anywhere.
The 'id' field probably just contains numbers. Yes?
If so, your links probably look something like http://example.com/123 which isn't going to go anywhere unless you have a controller named "123".
You need hrefs that go somewhere. I recommend using the anchor() function of Codeigniter URL Helper. You will need to load that helper before this example will work.
<?php foreach (get_categories_h() as $category) : ?>
<li class="list-group-item">
<?php echo anchor("controller_name/controller_method/{$category->id}", $category['name']); ?>
</li>
<?php endforeach; ?>
Without the anchor() function it would be written
<?php echo $category['name']; ?>
Try this:
<li class="list-group-item">
<a href="<?php echo $category->id;?>">
<?php echo $category['name']; ?>
</a>
</li>
I am having a blog page where the blogs are inserted from admin panel and blog title will be inserted into new column as separated by " - " if there are spaces between the page titles.For example if the page title is " welcome to something " then in the database it is will be inserted into two columns. In once column it will be inserted as same and in other column it will be inserted as welcome-to-something.
when clicking on readmore button i need to display in url as (www.example.com/blob/article/welcome-to-something) in this format i need to display the url.
Here is the code:
Controller:
public function index()
{
$this->load->model('blogs_model');
$data["records2"] = $this->blogs_model->get_all_blogs($config["per_page"], $page);
$data['mainpage'] = "blog";
$this->load->view('templates/template',$data);
}
public function article()
{
$this->load->model('blogs_model');
$data['records2']= $this->blogs_model->getblogsdata($this->uri->segment(3));
$data['mainpage']='blogs';
$this->load->view('templates/templatess',$data);
}
Model:
function get_all_blogs()
{
$this->db->select('B.*');
$this->db->from('blogs AS B');
$this->db->where(array('B.status'=>1));
$this->db->order_by("position", "asc");
$q = $this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
function getblogsdata($id)
{
$this->db->select('blogs.*');
$this->db->from('blogs');
$this->db->where(array('blogs.blog_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div class="col-md-9 blogs">
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="blog1">
<img src="<?php echo base_url();?>admin/images/blogimages/thumbs/<?php echo $r->image_path;?>" class="testimonials1"/>
<h3 class="heading1"><?php echo $r->blog_title;?></h3>
<div class="blogtext1 read">
<?php echo $r->description;?>
</div>
<a href="<?php echo base_url()?>blog/article/<?php echo $r ->blog_id ;?>" class="read_more7" target="_blank" >Read More</a>
</div>
<?php endforeach ;endif;?>
<div class="pagination"><?php echo $links; ?></div>
</div>
blogs table
blog_id | blog_title | blogtitle
1 welcome to something welcome-to-something
Model:
function getblogsdata($id,$slug)
{
$this->db->select('blogs.*');
$this->db->from('blogs');
$this->db->where(array('blogs.blogtitle'=>$id));
$this->db->where(array('blogs.blogtitle' => $slug));
$this->db->order_by("ne_views", "asc");
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<a href="<?php echo base_url()?>blog/article/<?php echo $r->blogtitle;?>" class="read_more7" target="_blank" >Read More</a>
i am getting an error "Message: Trying to get property of non-object"
when i try to display slider from database.
Message: Trying to get property of non-object
Filename: home/index.php
Line Number: 78
From admin side , admin enters slider name , image and Description and
it will display on user side at home page
At localhost (using wamp) it is working perfect but when i will upload online , it is giving error
Home.php ( Controller File )
if ( ! defined('BASEPATH'))
exit('No direct script access allowed');
class Home extends CI_Controller
{
public function index()
{
$this->load->view('home/index');
}
}
Index.php ( View File )
<div class="body_resize">
<div class="body">
<div class="border_box">
<div class="box_skitter box_skitter_large">
<?php
$info=$this->dbcommon->getInfo(array('homepage_image'),'homepage',array('status'=>0),'1','','sort_order');
foreach($info as $row)
{
print_r($row);
?>
<ul>
<li>
<img src="<?php echo homepage.'medium/'.$row->homepage_image ?>" class="cubeHide" alt="8_abs.jpg"
width="900" height="400" />
</li>
</ul>
<?php
}?>
</div>
</div>
<script src="js/jquery.skitter.js" type="text/javascript" defer="defer"></script>
<script type="text/javascript" defer="defer">
$(document).ready(function () {
var options = {};
if (document.location.search) {
var array = document.location.search.split('=');
var param = array[0].replace('?', '');
var value = array[1];
if (param == 'animation') {
options.animation = value;
}
else if (param == 'type_navigation') {
if (value == 'dots_preview') {
$('.border_box').css({ 'marginBottom': '40px' });
options['dots'] = true;
options['preview'] = false;
}
else {
options[value] = true;
if (value == 'dots') $('.border_box').css({ 'marginBottom': '40px' });
}
}
}
$('.box_skitter_large').skitter(options);
});
</script>
<div class="body_home">
<h4><strong>Welcome to Softloopers!</strong></h4>
<?php $info=$this->dbcommon->getInfo('','master','','','0,1','');
echo $info->homepage;
?><br />
</div>
getInfo function
function getInfo($field_name='',$table_name,$array='',$return="",$limit='',$orderby='')
{
if($field_name=='')
{
$sql='select * ';
}
else
{
$str='';
foreach($field_name as $row)
{
$str.=$row.',';
}
$str=rtrim($str,',');
$sql="select ".$str;
}
$sql.= ' from ' .$table_name .' where 2>0 ';
if($array!='')
{
foreach($array as $key=>$value)
{
$sql.="and $key='$value' and";
}
$sql=trim($sql,' and');
}
if($orderby!='')
{
$sql.=" order by $orderby";
}
if($limit!='')
{
$sql.=" limit $limit";
}
$query = $this->db->query($sql);
if($return=='')
{
return $query->row();
}
else
{
return $query->result();
}
}
If you want to pass data to view from controller, you can do like this
Home.php ( Controller File )
if ( ! defined('BASEPATH'))
exit('No direct script access allowed');
class Home extends CI_Controller
{
public function index()
{
$data['info']=$this->dbcommon->getInfo(array('homepage_image'),'homepage',array('status'=>0),'1','','sort_order');
$this->load->view('home/index');
}
}
Index.php ( View File )
<div class="box_skitter box_skitter_large">
<?php
foreach($info as $row)
{
print_r($row);
?>
<ul>
<li>
<img src="<?php echo homepage.'medium/'.$row->homepage_image ?>" class="cubeHide" alt="8_abs.jpg"
width="900" height="400" />
</li>
</ul>
<?php
}?>
</div>