Codeigniter foreach whithout $id - php

how i can sort some informations without $id? My problem is, that i ca read all teams and users. but how i can sort this?
So that i get a team and the players from this team in one box. WIth my code i have all users in all boxes.
Can i foreach in a foreach?
view what i try:
<?php foreach ($teams as $item): ?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php foreach ($users as $item): ?>
<div class="col-xs-12">
<?php echo $item->username ?>
</div>
<?php endforeach ?>
<?php endforeach ?>
This is my database
table users
user_id username team_id
1 paul 1
2 tom 2
3 brad 1
4 pim 2
table team
team_id teamname
1 team1
2 team1
Now i have a subside like domaincom/teams
And i want on this side
team 1 : paul, brad
team 2 : tom, pim
controller:
<?php
class Teams extends CI_Controller {
public $layout = 'full';
public $module = 'teams';
public $model = 'Teams_model';
public function __construct() {
parent::__construct();
$this->load->model($this->model);
$this->_primary_key = $this->{$this->model}->_primary_keys[0];
}
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$data['teamsWithUsers'] = $this->{$this->model}->get_users_by_team();
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
}
this is my model
<?php
class Teams_model extends CI_model
{
public $_table = 'teams';
public $_primary_keys = array('teams_id');
function get_teams()
{
return $this->db->get('teams')->result();
}
function get_users()
{
return $this->db->get('users')->result();
}
function get_users_by_team($teamID = null)
{
$this->db->select('u.user_id, u.username, u.team_id, t.teamname');
$this->db->from('users AS u');
$this->db->join('teams AS t', 't.team_id = u.team_id');
if ($teamID != '') {
$this->db->where('t.team_id', $teamID);
}
$this->db->order_by('t.teamname', 'ASC');
$this->db->order_by('u.username', 'ASC');
$query = $this->db->get();
return $query->result();
}
}
What i looking for is this view sample

what about that?
your controller
public function index()
{
$data['teams'] = $this->{$this->model}->get_teams();
$data['users'] = $this->{$this->model}->get_users();
$arrUsersPerTeam = [];
foreach($data['users'] AS $objUser)
{
$arrUsersPerTeam[$objUser->team_id][] = $objUser;
}
$data['arrUsersPerTeam'] = $arrUsersPerTeam;
$data['items'] = $this->{$this->model}->get();
$this->load->view($this->module, $data);
}
and your view
<?php
foreach ($teams as $item):
?>
<div class="col-xs-12">
<?php echo $item->teamname ?>
</div>
<?php
if (isset($arrUsersPerTeam[$item->team_id])) :
foreach ($arrUsersPerTeam[$item->team_id] as $objUser):
?>
<div class="col-xs-12">
<?php echo $objUser->username ?>
</div>
<?php
endforeach;
endif;
endforeach;

You should use a single join query to get your results make sure results are ordered by team
/**model*/
function some func(){
$this->db->select( 'u.username, t.team_id, t.teamname' );
$this->db->from( 'team AS t' );
$this->db->join( 'users AS u', 't.team_id = u.team_id' );
$this->db->order_by( 't.team_id', 'ASC' );
$query = $this->db->get();
return $query->result();
}
In your controller collect results returned by above method defined in your model and pass it to view.
In view there is no need for nested loop only single loop will do the job here like $results contains all the records then in view you can display your records as
/* view */
$parent = false;
$index = 1;
<div class="col-xs-12">
<?php foreach ($results as $result){ ?>
<?php if($parent !=$item->teamname ){ ?>
<?php if($index !=1 ){ ?>
</div>
<?php } ?>
<div class="col-xs-12">
<h2><?php echo $result->teamname ?></h2>
<?php } ?>
<p><?php echo $result->username ?></p>
<?php
$parent =$result->teamname;
$index++;
} ?>
</div> // To close the opened div

2 things: you can pick out key from the foreach, that you can use later, second the "$item" is used 2 places where you might overwrite it by accident.
<?php foreach ($teams as $key => $team_item ): ?>
<div class="col-xs-12">
<?php echo $team_item->teamname ?>
</div>
<?php foreach ($users as $user_item): ?>
<?php if($item->team_id == $key): ?>
<div class="col-xs-12">
<?php echo $user_item->username ?>
</div>
<?php endif ?>
<?php endforeach ?>
<?php endforeach ?>
I'm not really sure if thats what you are trying to achieve

Related

CodeIgniter - joining users, posts, comments tables

im joining 3 tables: users, posts and comments in the following code :
public function join_user_post(){
$this->db->select('
posts.post_body,
posts.date_created,
users.username,
users.user_image,
comments.comment_body,
comments.date_created
');
$this->db->from('posts');
$this->db->join('users', 'users.id = posts.post_user_id ');
$this->db->join('comments', 'comments.comment_post_id = posts.post_id ');
$query = $this->db->get();
return $query->result();
}
then passing this array data to the homepage view via controller:
<?php
class Home extends CI_Controller{
public function index(){
$this->load->model('user_model');
$data['posts'] = $this->user_model->join_user_post();
$this->load->view("user/homepage",$data);
}
}
?>
in the homepage view im trying to echo the post with the username and user image, then looping through comments of each post and echo it out
<body>
<?php include 'navbar.php';?>
<?php foreach($posts as $post): ?>
<div>
<img src="<?php echo $post->user_image ?><br>">
<?php echo $post->username ?><br>
<?php echo $post->post_body ?><br>
<?php echo $post->date_created ?><br>
<?php foreach($posts as $post): ?>
<?php echo $post->comment_body ?><br>
<?php echo $post->date_created ?><br>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</body>
but im rather getting all comments on every post instead of getting the comments that are related to specific post id, the foreach is looping through all comments and echo them on every post, if i remove the foreach loop it will echo only one comment at each post
what should i do to solve this issue?
The problem is when you join posts with comments it return many records of comments with the same post. You can modify a little bit first in your controller to store each post with comments belong to it:
function index()
{
$this->load->model('user_model');
$comments = $this->user_model->join_user_post();
$posts = array();
foreach ($comments as $comment) {
if (array_key_exists($comment->post_id, $posts)) {
$posts[$comment->post_id]['comments'][] = $comment;
} else {
$posts[$comment->post_id]['post_body'] = $comment->post_body;
$posts[$comment->post_id]['username'] = $comment->username;
$posts[$comment->post_id]['date_created'] = $comment->date_created;
$posts[$comment->post_id]['user_image'] = $comment->user_image;
$posts[$comment->post_id]['comments'][] = $comment;
}
}
$data['posts'] = $posts;
$this->load->view("user/homepage", $data);
}
And in your view:
<div>
<img src="<?php echo $post['user_image'] ?><br>">
<?php echo $post['username'] ?><br>
<?php echo $post['post_body'] ?><br>
<?php echo $post['date_created'] ?><br>
<?php foreach ($posts['comments'] as $comment) : ?>
<?php echo $comment->comment_body ?><br>
<?php echo $comment->date_created ?><br>
<?php endforeach; ?>
</div>

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; } ?>

my query in codeigniter cannot produce result

i've been debbuging it many times based on my knowledge, i am new to codeigniter, any solution idea would be much appreciated... ty
here's my code
MODEL:
function userdisplay_info($id){
$result = $this->db->query("SELECT uid FROM user WHERE userIdentificationNumber LIKE '$id'");
//if($result->num_rows() > 0){
$info_data = $result->result();
$row = $info_data[0];
$result->free_result();
}
CONTROLLER:
function r_book(){
$data = array();
$bid = $this->input->post('bid');
$u_id = $this->input->post('userinputid');
$data = array(
'book_reserved' => 1
);
if($this->module2->reserved_book($bid,$data))
{
$data['info'] = $this->module2->userdisplay_info($u_id);
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpage',$data);
$this->load->view('User/template/footer');
return true;
}else
{
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpagefail');
$this->load->view('User/template/footer');
return false;
}
}
VIEW:
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<?php if($info) : foreach($info as $u_info) : ?>
<ul class="list-unstyled">
<li>Last Name : <?php echo $u_info->uid; ?></li>
<li>First Name : <?php echo $u_info->userFirstname; ?></li></li>
<li>Middle Name : <?php echo $u_info->userMiddlename; ?></li></li>
<li>Course : <?php echo $u_info->userCourse; ?></li></li>
</ul>
<?php endforeach; ?>
<?php else :?>
<h4> No Record Found</h4>
<?php endif; ?>
</div>
</div>
</div>
Rewrite your model function as
function userdisplay_info($id){
$this->db->select('uid');
$this->db->like('userIdentificationNumber', $id);
$query = $this->db->get('user');
return $query->result_array();
}

query result using codeIgniter

It is the first time for me to use codeIgniter, I tried to build a simple DB driven application.
First the model:
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news()
{
$query = $this->db->get('news');
return $query->result_array();
}
}
second the controller
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
The view "index":
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
When I run the code it displays the header and the footer, but no database record is displayed.
If I put a print statement in the view outside the foreach it works, but not inside the foreach.
I use if($news) to find out if the query retrieved any result, but there is no result retrieved.
How can I know why there is no result retrieved from the DB?
You need to call another foreach inside your foreach. example:
foreach ($result as $row) {
foreach ($row as $key => $val) {
if ($key === "reservation_info") {
$data['decoded'] = json_decode($val);
} else {
$data[$key] = $val;
}
}
}
and i would use the '$val' values in the view. just by calling them as variables, like so
//in the view
echo $decoded
echo $firtname
... and so on
to check if new is empty or not, just
print_r($news);
or you can modify your view :
<?php if(!empty($new)): ?>
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<?php endforeach ?>
<?php else: ?>
Empty news
<?php endif; ?>

Very slow when getting data from class

I have created a class, it store the data from mySQL database into class.
The performance is really slow when outputting to the browser, I have to wait like 10 seconds and this is not acceptable. How to solve this problem?
In the controller file:
$modelCategory = new modelCategory();
$categories = $modelCategory->findAll('takeawayID = :id', array('id' => $takeawayID));
if ($categories === false) {
echo "Query failed";
return;
}
$data['categories'] = $categories;
View File:
<?php foreach ($categories as $category): ?>
<div class="menu-container">
<h2><?php echo $category->name; ?></h2>
<ul class="menu-list">
<?php foreach ($category->item as $item): ?>
<li class="<?php echo $class; ?>">
<div class="menu-holder">
<div class="text-block">
<div class="text-holder">
<?php if ($item->optionsTotal == 1): ?>
<?php foreach($item->options as $option): ?>
<?php $price = $option->price; ?>
<?php $optionvalue = $option->optionValue; ?>
<?php endforeach; ?>
<?php endif; ?>
<h3>
<?php echo $item->name; ?>
<?php if ($item->optionsTotal == 1 && $optionvalue != "Regular"): ?>
(<?php echo $optionvalue; ?>)
<?php endif; ?>
</h3>
<?php if ($item->desc != ""): ?>
<p> <?php echo $item->desc; ?> </p>
<?php endif; ?>
</div>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
model Category class file:
<?
class modelCategory extends Model {
public $id;
public $desc;
public $name;
public $items = null;
public function findAll($condition, $parameters) {
$query = "SELECT * FROM categories WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
return self::createModels($statement->fetchAll());
}
public static function createModels($dataAr) {
$models = array();
foreach ($dataAr as $data) {
$category = new modelCategory;
$category->id = $data['id'];
$category->desc = $data['description'];
$category->name = ucwords(strtolower($data['name']));
$models[] = $category;
}
return $models;
}
public function getItems() {
if ($this->items === null)
$this->items = modelItem::find('category_id = :category_id', array('category_id' => $this->id));
return $this->items;
}
public function __get($key) {
switch ($key) {
case 'item':
return $this->getItems();
}
}
}
?>
modelItem:: class is very similar to model Category class.
one problem that I see is that you take the result and build a class to contain the data you could use PDO::FETCH_CLASS that does the same but in a more optimize way.
But like Michael J.V. said you should do some monitoring of your application to detect the exact cause of the problem (there might be multiple and not easy to catch with the eyes)

Categories