Display data from three tables with common id in foreach - php

So I currently have three tables like this given below:
AI = auto increment.
ci_users: user_id(AI), username, slug, email, biography.
ci_terms: term_id(AI), title, slug, body.
ci_relationship: id(AI), term_id, user_id, type.
I'm trying to display all the users from a specific term_id(where type is skill),
for example, let's say term_id 3(where term_id has the title of 'CSS' from ci_terms).
To make it more clear,the above paragraph basically says show me all users with skill of CSS but I want the displayed users to show all of their other skills which are stored in the ci_relationship table.
PARAGRAPHS BELOW ARE AFTER CLICKING A SPECIFIC TERM_ID(SKILL).
This is the function which shows me all of the users that have the term_id as their skill.(from my previous Stackoverflow question. Thanks to pradeep who helped me solve that query:
// All users with specific skill
public function get_user_skill($id)
{
$this->db->select('*, count(ci_relationship.term_id)');
$this->db->from($this->table);
$this->db->join('ci_relationship', 'ci_relationship.user_id = ci_users.id', 'INNER');
$this->db->order_by('ci_relationship.user_id', 'DESC');
$this->db->group_by('ci_relationship.user_id');
$this->db->where('ci_relationship.term_id', $id);
$this->db->where('ci_relationship.type', 'skill');
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
As I said before the code above just display the users with the specific term_id. Now this is the method in the controller which shows the expected data(users with specific term_id):
This is my controller :
public function skill($id){
// Get data
$data['users'] = $this->User_model->get_user_skill($id);
$term = $this->Terms_model->get($id);
// Get skill name
$data['skill'] = $this->Terms_model->get($id);
// Get skills per foreach --- HERE IS WHERE I NEED HELP
$data['skills'] = $this->User_model->skills($id);
// Meta
$data['title'] = $this->settings->title.' | '. ucfirst($term->title);
// Load template
$this->template->load('public', 'default', 'users/skill', $data);
}
This is the method that I'm trying to create to displayed the term_id per user_id:
// Skill for user foreach
public function skills($id){
$this->db->select('*');
$this->db->from($this->relationship);
$this->db->where('term_id', $id);
$this->db->where('type', 'skill');
$this->db->order_by('id', 'DESC');
$query = $this->db->get();
if($query->num_rows() >= 1){
return $query->result();
} else {
return false;
}
}
The view is the following code:
<?php if($users) : ?>
<div class="row">
<?php foreach($users as $user) : ?>
<div class="col-lg-3 col-sm-6">
<div class="card text-center panel">
<div class="cardheader panel-heading" style="background: url(<?php if($user->user_id) : echo base_url('assets/img/users/covers/'.get_username($user->user_id).'/'.get_username_cover($user->user_id)); else : echo base_url().'assets/img/noavatar.jpg'; endif ?>)no-repeat center center;"></div>
<div class="avatar">
<a target="_self" href="<?= base_url('users/profile/'.get_username($user->user_id)); ?>"><img class="img-circle" alt="<?= get_username($user->user_id); ?> profile picture" title="<?= get_username($user->user_id); ?> profile picture" src="<?php if($user->user_id) : echo base_url('assets/img/users/avatars/'.get_username($user->user_id).'/'.get_username_avatar($user->user_id)); else : echo base_url().'assets/img/noavatar.jpg'; endif ?>"></a>
</div>
<div class="info panel-body">
<div class="title">
<a target="_self" href="<?= base_url('users/profile/'.get_username($user->user_id)); ?>"><?= get_username($user->user_id); ?></a>
</div>
<div class="desc"><?php if(get_occupation($user->user_id)) : ?><?= get_occupation($user->user_id); ?><?php else : echo 'No Job'; endif ?> <?php if(get_company($user->user_id)) : ?> - <b><?= get_company($user->user_id); ?></b><?php else : echo '- <b>No Company</b>'; endif ?></div>
<!-- BEGINNING OF HERE IS WHERE I NEED HELP -->
<?php if($skills) : ?>
<?php foreach($skills as $skill) : ?>
<span class="label label-orange"><?= get_term($skill->term_id) ?></span>
<?php endforeach ?>
<?php endif ?>
<!-- END OF HERE IS WHERE I NEED HELP -->
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else : ?>
<div class="alert alert-danger">No user with <?= $skill->title ?> skill found</div>
<?php endif; ?>
This is the actual output:
And this is the expected output:
I hope I could explain myself well enough to make it easy to understand,thanks in advance.

Hope this will help you :
Create a helper method get_skill_by_user just like get_username or get_occupation and use it in your view
function get_skill_by_user($user_id, $id)
{
$ci = & get_instance();
$ci->db->select('*');
$ci->db->from('ci_relationship');
$ci->db->where('term_id', $id);
$ci->db->where('user_id', $user_id);
$ci->db->where('type', 'skill');
$ci->db->order_by('id', 'DESC');
$query = $ci->db->get();
if($query->num_rows() > 0)
{
return $query->result();
} else
{
return false;
}
}
In your view your skills loop should be like this :
<?php $user_skills = get_skill_by_user($user->user_id, $user->term_id); if($user_skills) : ?>
<?php foreach($user_skills as $skill) : ?>
<span class="label label-orange"><?= get_term($skill->term_id) ?></span>
<?php endforeach ?>
<?php endif ?>

Related

Category product menu bar not linking

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>

How to pass two different ids of different models from a controller to a view

I am having an issue with passing two ids in blog posts. The first id
displays a single post and the second one counts the number of posts.
Each works well separately but on integrating the two, it selects a
wrong post.
This is my code for the first model that fetches the comments
class News_model extends CI_Model {
function get_comment($id)
{
$this->db->select('comments.*,users.username');
$this->db->from('comments');
$this->db->join('users','users.id = comments.user_id', 'left');
$this->db->where('post_id',$id);
$this->db->order_by('date_added','asc');
$query = $this->db->get();
return $query->result_array();
}
}
This is the model that fetches the posts
class News_model extends CI_Model {
function get_one_news($news_id)
{
$this->db->select('*, news.id as id');
$this->db->from('news');
$this->db->join('users' , 'users.id = news.user_id');
$this->db->where('news.id' , $news_id);
$query = $this->db->get();
return $query->first_row('array');
}
function latestnews() {
$this->db->select("
news.*,users.*,comments.*,COUNT(comments.post_id) AS num_comments");
$this->db->from('news');
$this->db->join('users' , 'users.id = news.user_id');
$this->db->join('comments' , 'comments.post_id = news.id');
$this->db->group_by('comments.post_id');
$this->db->order_by('news.date_added','desc');
$this->db->limit(4);
$query = $this->db->get();
return $query->result_array();
}
}
And here is my controller
function view($id)
{
$data['news'] = $this->news_model->get_one_news($id);
$data["latest_news"] = $this->news_model->latestnews();
$data['comments'] = $this->m_comment->get_comment($id);
$data['content'] = 'single'; // template part
$this->load->view('includes/template',$data);
}
And finally the view file
<div id="sidebar" class="col-md-3 fix-left">
<!---- Start Widget ---->
<div class="widget wid-vid">
<div class="heading">
<h4>Latest News</h4>
</div>
<div class="content">
<div class="tab-content">
<div id="most" class="tab-pane fade in active">
<div class="post wrap-vid">
<?php if(count($latest_news)) {
foreach($latest_news as $l_news){ ?>
<div class="zoom-container">
<div class="zoom-caption">
</div>
<img src="<?php echo base_url('assets/images/'.$l_news['image'])?>"
style="height:80px;width:100px;"/>
</div>
<div class="wrapper">
<h5 class="vid-name"><a href="<?php echo base_url('bulletins/view/'.$l_news['id'])?>"><?php echo
substr(strip_tags($l_news['title']), 0, 15).'..';?></a></h5>
<div class="info">
<h6>By <?php echo $l_news['username']?></h6>
<span><i class="fa fa-calendar"></i><?php echo date( 'F jS, Y' , strtotime($l_news['date_added']))?></span>
<span><i class="fa fa-comment-o">/i><?php echo
$l_news['num_comments'];?></span>
</div>
</div>
<?php }}?>
</div>
</div>
</div>
</div>
</div>
Please check below mentioned solution. You have error in your select cause. When you want data from multiple table in CI and if columnName is same than CI query builder will overwrite value of that column. In this case you need to give alias to columnName. Please check below.
$this->db->select('news.id as newsId,users.id as userId,news.*,users.*,comments.*, COUNT(comments.post_id) as num_comments');
And in your view file you need to change below code.
Find $l_news['id'] and replace with $l_news['newsId']
This will resolve your issue. Let me know if it not works for you.

Warning: Invalid argument supplied for foreach()

I have an error in the product detail, I do not know what else to change where again. when I change $detail into $categories succeed but is the same as function submenu. It was not according to my wishes
My View
<!-- navbar -->
<div class="row">
<?php foreach ($categories as $row) : ?>
<div class="col-sm-3">
<h5><?php echo $row->categoriesName; ?></h5>
<ul><li><a href="<?php echo base_url();?>member/detail">
<?php echo $row->productName; ?></a> </li></ul>
</div>
<?php endforeach; ?>
</div>
<!-- product detail -->
<?php foreach ($detail as $details_new) : ?>
<div class="box">
<h1 class="text-center"><?php echo $details_new->productName;?></h1>
<p class="price"><?php echo $details_new->price;?></p>
</div>
<?php endforeach; ?>
My Controller
public function home() {
$data=array('title'=>'Pasar Online | Ayo Belanja Sekarang',
'username'=> $this->session->userdata('username'),
'product' => $this->product_model->all(),
'categories' => $this->categories_model->get_main(),
'isi' =>'member/index');
$this->load->view('template_home/wrapper',$data);
}
public function detail() {
$data['username'] = $this->session->userdata('username');
$data['categories'] = $this->categories_model->get_main();
$data['detail'] = $this->categories_model->get_details();
$this->load->view('member/coba',$data);
}
My Model
public function get_main(){
$this->db->select('product.*,categories.*');
$this->db->from('product');
$this->db->join('categories','product.categoriesID=categories.categoriesID');
$this->db->limit(5);
$query = $this->db->get();
if($query->num_rows() > 0) {
$results = $query->result();
} return $results;
}
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
}
still can not display a single product
I do not know where my mistake... please help me, thanks
you are iterating details array in wrong format.
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
return $row;
}
This will return only single row without any indexing like - 0,1,2...
and on view page you are using foreach loop and foreach loop use indexing to iterate value you can iterate like that --
<div class="box">
<h1 class="text-center"><?php echo $detail->productName; ?></h1>
<p class="price"><?php echo $detail->price; ?></p>
</div>
please use this way hope it will work..
In codeigniter row() selects only first row of your result in object format.So no need to use foreach loop.Just try like this...
<div class="box">
<h1 class="text-center"><?php echo $detail->productName;?></h1>
<p class="price"><?php echo $detail->price;?></p>
</div>
And
In model
public function get_details() {
$query = $this->db->query("SELECT * FROM product WHERE productID");
$row = $query->row();
return $row;
}
it is because of $detail variable is empty, no data available in this variable, always check for data in variable before looping
<?php if(!empty($detail)){
foreach ($detail as $details_new) : ?>
<div class="box">
<h1 class="text-center"><?php echo $details_new->productName;?></h1>
<p class="price"><?php echo $details_new->price;?></p>
</div>
<?php endforeach; } ?>

Active Records getting second table values in CodeIgniter

I create just a simple blog and I can't get my desired output from the post, all I wanted is I want to get the firstname and lastname from the second table by using the userID from the first table.
controllers/posts.php:
<?php
class Posts extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('post');
}
function index() {
$data['posts'] = $this->post->get_posts();
$data['users'] = $this->post->get_users();
$this->load->view('post_index', $data);
}
function post($postID) {
$data['post'] = $this->post->get_post($postID);
$this->load->view('post', $data);
}
function correct_permissions($required) {
$user_type = $this->session->userdata('user_type');
if ($required == "User") {
if ($user_type) {
return true;
}
} elseif ($required == "Blogger") {
if ($user_type == "Blogger") {
return true;
}
}
}
function deletepost($postID) {
$user_type = $this->session->userdata('user_type');
if ($user_type != 'Blogger') {
echo "<script>alert:('Please log in to continue.');</script>";
redirect(base_url());
}
$this->post->delete_post($postID);
redirect(base_url() . 'posts');
}
}
models/post.php
<?php
class Post extends CI_Model{
function get_posts($num=50,$start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query = $this->db->get();
return $query->result_array();
}
function get_post($postID){
$this->db->select()->from('posts')->where(array('active'=>1,'postID'=>$postID))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function get_user($userID){
$this->db->select()->from('users')->where(array('userID'=>$userID));
$query=$this->db->get();
return $query->first_row('array');
}
function get_users(){
$userID = $this->session->userdata('userID');
$this->db->select('firstname','lastname')->from('users')->where('userID',$userID);
$query = $this->db->get();
return $query->result_array();
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->insert_id();
}
function update_post($postID,$data){
$this->db->where('postID',$postID);
$this->db->update('posts',$data);
}
function delete_post($postID){
$this->db->where('postID',$postID);
$this->db->delete('posts');
}
}
and my code from views/post_index.php
<div class="panel">
<?php if (!isset($posts)) { ?>
<p>There are currently no posts on my blog.</p>
<?php
} else {
foreach ($posts as $row) {
?>
<div class="panel-heading">
<h2 href="<?= base_url() ?>posts/post/<?= $row['postID'] ?>"><?= $row['title'] ?></h2>
</div>
<div class="panel-body">
<p><?= substr(strip_tags($row['post']), 0, 200) . "..." ?></p>
<br><br>
<div class="panelver">
<h6 href="<?= base_url() ?>posts/post/<?= $row['userID'] ?>">Posted by:
<?php
if($row['userID'] == 0) {
echo "Someone";
} else {
echo $this->db->select('firstname','lastname')->from('users')->where('userID',$row['userID']);
}
?></h6>
<p href="<?= base_url() ?>posts/post/<?= $row['postID'] ?>">Added last: <?= $row['date_added'] ?></p>
</div>
<p>Read More - - - Edit | Delete</p>
<hr/>
</div>
<?php
}
}
?>
</div>
The output:
Blog Posts
this is a post blah, blah, blah..... the "posted by:" must output the
author name getting userID from the second table value using the
userID from the first table as the output below, help me! T_T...
Posted by: 2
Added last: 2014-09-20 11:30:00
Read More - - - Edit | Delete
but when I do this code:
<div class="panel">
<?php if (!isset($posts)) { ?>
<p>There are currently no posts on my blog.</p>
<?php
} else {
foreach ($posts as $row) {
?>
<div class="panel-heading">
<h2 href="<?= base_url() ?>posts/post/<?= $row['postID'] ?>"><?= $row['title'] ?></h2>
</div>
<div class="panel-body">
<p><?= substr(strip_tags($row['post']), 0, 200) . "..." ?></p>
<br><br>
<div class="panelver">
<h6 href="<?= base_url() ?>posts/post/<?= $row['userID'] ?>">Posted by:
<?php
if($row['userID'] == 0) {
echo "Someone";
} else {
echo $this->db->select('firstname','lastname')->from('users')->where('userID',$row['userID']);
}
?></h6>
<p href="<?= base_url() ?>posts/post/<?= $row['postID'] ?>">Added last: <?= $row['date_added'] ?></p>
</div>
<p>Read More - - - Edit | Delete</p>
<hr/>
</div>
<?php
}
}
?>
</div>
this will happen:
Blog Posts
this is a post blah, blah, blah..... the "posted by:" must output the author name getting userID from the second table value using the userID from the first table as the output below, help me! T_T...
The "posted by:" must output the author name getting userID from the second table value using the userID from the first table as the output below.
Posted by:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_driver could not be converted to string
Filename: views/post_index.php
Line Number: 42
Added last: 2014-09-20 11:30:00
Read More - - - Edit | Delete
P.S: I'm a beginner programmer and new to CodeIgniter.
Ok.So what i get from your question is you have two tables with userId stored in one and user details in another.So try this as you need to get the row before echoing it.
echo $this->db->select('firstname','lastname')->from('users')->where('userID',$row['userID'])->get()->row();
the above code can also be written like this :
$this->db->select('firstname','lastname')->where('userID',$row['userID'])->get('users')->row();
Let me know if you have any doubts.

SELECT COUNT(*) FROM 'accounts' WHERE role = 'engineer' getting the total number of rows using symfony1.4

Hi i have a problem in getting all the data from the table accounts, I want to get the total number of data's from the table accounts using WHERE. Let's say from the table accounts where role = engineer. all the total number of rows from the field role = engineer will get. Im using symfony framework on this
Here's my controller below
<?php
class spFindRoleDetailAction extends sfAction{
function preExecute(){
}
public function execute($request){
$this->setLayout('spLayout');
$this->setTemplate('sp/roleDetail');
$role = $request->getParameter('ro');
$this->roleDetail = AccountTable::getInstance()->getRoleDetail($role);
$this->roleCount = AccountTable::getInstance()->getCountDetail($role);
}
}
Model query
public function getCountDetail($role){
return $this->createQuery('a')
->where('a.role = ?', $role)
->execute();
}
and my module templates view code here
<div id="search-by-role-detail" data-role="page">
<div role="main">
<ul data-role="listview">
<li>
<a href="<?php echo url_for('#find-sp-role-page'); ?>" class="ui-btn ui-btn-icon-left ui-icon-nav-l center">
<h1>エンジニア<span class="header-result-count">(<?php echo $roleCount->count(); ?>)</span></h1>
</a>
</li>
<?php if(isset($roleDetail)): ?>
<?php foreach($roleDetail as $role): ?>
<li>
<a href="<?php echo $role->getSlug(); ?>"class="ui-btn ui-btn-icon-right ui-icon-list-r" data-transition="slide">
<?php if($role->getLogo() == NULL): ?>
<div class="middle v-image">
<img class="image-user" src="/images/sp/sample.png">
</div>
<?php else: ?>
<div class="middle v-image">
<img class="image-user" alt="<?php echo $role->getName(); ?>" src="http://img.creww.me/uploads/account/logos/<?php echo $role->getLogo(); ?>">
</div>
<?php endif; ?>
<div class="middle v-list">
<h3><?php echo $role->getName(); ?></h3>
<p><?php echo $role->getOverview(); ?></p>
</div>
</a>
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
</div>
The one in the H1 tag there is a count in there, How will i able to get the total number of rows in it. Im using there a <?php echo $roleCount->count(); ?> which is wrong
Anyone can help me out on this??
Any help is muchly appreciated
Thanks!
If count() isn't working then you can try something like this.
public function getCountDetail($role)
{
$q = Doctrine_Query::create()
->from('[some table] a')
->where('a.role = ?', $role)
->select('COUNT(a.id)')
->execute(array(),Doctrine_Core::HYDRATE_SINGLE_SCALAR)
return $q;
}
In this case the function will return a single number representing the number of records found.

Categories