CodeIgniter: Displaying data from two tables in one loop - php

Let's say I have these two database tables:
blog comments
------- ----------
blog_id comment_id
title blog_id
content comment
Now I'd like to run through the 3 latest blog entries and display the title, content and the number of comments made on that entry.
For that, I created a Blog_model:
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$this->db->order_by("blog_id", "desc");
$q = $this->db->get('blog', $n);
if($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
The model is loaded in the controller and passed on to the view:
$this->load->model('Blog_model');
$data['blog_rows'] = $this->Blog_model->get_entries(3);
$this->load->view('blog_view');
That gives me the three latest blog entries. I can now loop through the rows and display the content in the view like this:
<?php foreach ($blog_rows as $row): ?>
<h2><?=$row->title;?></h2>
12>
<p><?=$row->content;?></p>
<?php endforeach; ?>
So far so good. But now the tricky part:
I'd like to display the number of comments associated with the displayed blog entry. How would I accomplish that, adhering to the CodeIgniter practices?

Here are two proposals for the model method: the first does a query for each blod row, while the second does an unique query wich is faster. the second query is not tested.
Model 1
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$this->db->order_by("blog_id", "desc");
$q = $this->db->get('blog', $n);
if($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
foreach($data AS &$blog_e)
{
$q = "SELECT COUNT(*) AS count FROM comments WHERE blog_id = ?";
$query = $this->db->query($q,array($blog_e->blog_id);
$ncomments = $query->result_array();
$blog_e->n_comments = $ncomments[0]['count'];
}
}
Model 2
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$q = "SELECT blog.blog_id,title,content,COUNT(comment_id) AS n_comments
FROM blog JOIN comments ON blog.blog_id = comments.blog_id
GROUP BY blog.blog_id,title,content
ORDER BY blog.blog_id DESC
LIMIT 0,?"
$query = $this->db->query($q,array($n));
if($query->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
View
<?php foreach ($blog_rows as $row): ?>
<h2><?=$row->title;?></h2>
<?=$row->n_comments?>>
<p><?=$row->content;?></p>
<?php endforeach; ?>

Related

->result() not showing all data/rows

I have a question
Let say we have this 2 tables in our database
first table : category_lists
second table: data_category
so if list_data_id is equal to 1 meaning that it has 2 data if you look at data_category table which is 6 and 7
Now what I want is to query from category_list table so that 6 and 7 will echo Car Wreckers and Cash For Cars.
This is what my code looks like:
below is my controller:
public function index($listing_name)
{
$this->load->view('layouts/head_layout_seo');
$this->load->view('layouts/head_layout');
$data['main_view'] = 'listings/main_view';
$data['listing_data'] = $this->Listing_model->get_detail_listing($listing_name);
$list_id = $data['listing_data']->list_data_id; // this is what I get list_data_id is equal to 1
$data['category_ads'] = $this->Ads_model->get_ads($list_id); // this is what you need to look
$this->load->view('layouts/main', $data);
$this->load->view('layouts/footer_layout');
}
below is my model:
public function get_ads($list_id)
{
$this->db->where('list_data_id', $list_id);
$query = $this->db->get('data_category');
$query = $query->result();
//return $query;
if (count($query) > 0) {
for ($i=0; $i < count($query); $i++) {
foreach ($query as $value) {
$this->db->where('category_lists_id', $value->category_lists_id);
$querys = $this->db->get('category_lists');
//print_r($query);
return $querys->result();
}
}
}
}
below is my view:
foreach ($category_ads as $value) {
<p><?php echo $value->categories; ?></p> }
with the code above I get only 1 data which is Car Wreckers as you can see from the table, it supposes to show 2 data Car Wreckers and Cash For Cars
Can anyone help me with this?
Thank You
Try this, in your model so no need to call DB two times and no need to loop
public function get_ads($list_id)
{
$this->db->select('cl.category_lists_id,cl.categories');
$this->db->from('category_lists cl');
$this->db->join('data_category dc','cl.category_lists_id = dc.category_lists_id');
$this->db->where('dc.list_data_id',$list_id);
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result();
}else{
return array();
}
}

push array data in every index of an array using codeigniter php

I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}

Multiple foreach - first result not displaying

I am playing around with the below code, I am making my personal "music database". In my mysql I have the following tables:
Music Categories
Music Artists
Music Tracks
The code below works fine except it doesn't display the first track of the database, it skips it, but it displays all the rest just fine. If I take the below example, the data displayed is as follows:
Category: 70's
artist2 trackname2
Category: 90's
artist3 trackname3
So, the first track get's skipped. I have been playing around with the code, but I cannot get it to work. It should be displayed like this:
Category: 70's
artist1 trackname1
artist2 trackname2
Category: 90's
artist3 trackname3
Example of how it looks like in the database:
music_categories:
musicID name
1 70s
2 80s
3 90s
music_artists:
artistID name
1 artist1
2 artist2
3 artist3
music_tracks:
id musicID artistID track
1 1 1 trackname1
2 1 2 trackname2
3 3 1 trackname3
Each music track has one artist and one category. I am using the code below in my classes.php file:
public function grabResults($table)
{
$result = 'SELECT * FROM '.$table;
$query = $this->mysqli->query($result);
if($query)
{
while($row = $query->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
else {
return false;
}
}
And this is the code itself:
$categories = $data->grabResults(music_categories);
$artists = $data->grabResults(music_artists);
$tracks = $data->grabResults(music_tracks);
$catName = '';
$counter = 0;
foreach ($categories as $category)
{
foreach ($tracks as $track)
{
if($category['name'] != $catName)
{
$countID = $category['id'];
$total = $data->mysqli->query("SELECT `musicID` FROM `music_tracks` WHERE `musicID` = '$countID' ");
$totalCount = $total->num_rows;
if($totalCount > 0)
{
echo $category['name'];
}
$catName = $category['name'];
$counter = 0;
}
if($counter > 0)
{
if($category['id'] == $track['mid'])
{
foreach ($artists as $artist)
{
if($track['artistID'] == $artist['id'])
{
echo $artist['name'];
}
}
echo $track['track'];
echo "<br>";
}
}
$counter++;
}
}

Total unpublished occurances across multiple tables using a loop and array

I have a function that gets the number of unpublished records from a table (which works fine). However now I want to get the total number of unpublished occurances in multiple tables. I figure I can do a foreach loop using the $tables = array('projects', 'testimonials') .etc. then add together their respective results to get total number and return that? However I am not sure how to do this, this kindof loop is a bit outside my abilities.
function publishCount($table) {
$sql = mysql_query("SELECT COUNT(*) AS nb FROM ".$table." WHERE published='0' OR published=''") or die(mysql_error());
$result = mysql_result($sql, 0);
if (!$result == 0) { echo 'Awaiting to be published <span class="badge badge-important">'.$result.'</span>'; }
else { echo 'Awaiting to be published <span class="badge badge-inverse">'.$result.'</span>'; }
}
You should edit your function this way:
function publishCount($table) {
$sql = mysql_query("SELECT COUNT(*) AS nb FROM ".$table." WHERE published='0' OR published=''") or die(mysql_error());
$result = mysql_result($sql, 0);
return $result;
}
So you can then do a loop through your $tables list:
$tables = array('projects', 'testimonials', [...]);
$nbResults = 0;
foreach($tables as $table) {
$nbResults += publishCount($table);
}
if($nbResults == 0) {
// ...
} else {
// ...
}

Printing the Categories and Sub Categories Alone

function build_list($id=0,$collapsed="") //return an array with the categories ordered by position
{
$RootPos = "";
$this->c_list = array();
if($id != 0){
$this_category = $this->fetch($id);
$positions = explode(">",$this_category['position']);
$RootPos = $positions[0];
}
// lets fetch the root categories
$sql = "SELECT *
FROM ".$this->table_name."
WHERE position RLIKE '^([0-9]+>){1,1}$' AND c_group = '".$this->Group."'
ORDER BY c_name";
$res = mysql_query($sql) or die(trigger_error("<br><storng><u>MySQL Error:</u></strong><br>".mysql_error()."<br><br><storng><u>Query Used:</u></strong><br>".$sql."<br><br><storng><u>Info:</u></strong><br>",E_USER_ERROR));
while($root = mysql_fetch_array($res)){
$root["prefix"] = $this->get_prefix($root['position']);
$this->c_list[$root['id']] = $root;
if($RootPos == $root['id'] AND $id != 0 AND $collapsed != ""){
$this->list_by_id($id);
continue;
}else{
// lets check if there is sub-categories
if($collapsed == "" AND $id==0){
$has_children = $this->has_children($root['position']);
if($has_children == TRUE) $this->get_children($root['position'],0);
}}}
return $this->c_list;
}
// He is the Author of the code...
Categories Class
Author: Shadi Ali
Now I want to just return the Categories and Sub Categories from the above code.
function browse() {
$categories = new categories;
$categories_list = $categories->build_list();
foreach($categories_list as $c)
{
return $c->$id;
}
}
The above code is not working.... can anyone help me out.
Here are two problems with the browse() function:
The return statement is inside the foreach loop. The statement will return one value for one of the items in the $categories-list (at most), and not continue to loop over the rest of the $categories-list.
The $id variable is never declared or initialised in return $c->$id, perhaps you meant to use $c['id'] or $c->id

Categories