Multiple foreach - first result not displaying - php

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

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

PHP MySQL Multidimensional Array - Dropdown Menu

I want to create my dropdown menu from a mysql query, but i'm having trouble with the sub-items.
My basic table:
NavigationID ParentID Name Url
1 1 Home home
2 2 About about
3 3 Products products
4 3 Category1 #
5 3 Category2 #
6 4 Product1 #
7 5 Product2 #
My simple MySQL Query and adding to array:
class Navigation{
private $data;
public function __construct($par){
if(is_array($par))
$this->data = $par;
}
public function __toString(){
return '<li>'.$this->data['Name'].'</li>';
}
}
$query = mysql_query("SELECT * FROM Navigation n") or die(mysql_error());
$num = mysql_num_rows($query);
$menuitems = array();
while($row = mysql_fetch_assoc($query)){
$menuitems[] = new Navigation($row);
}
echo '<div id="nav"><ul>';
foreach($menuitems as $item){
echo $item;
}
echo '</ul></div>';
The result of this is:
<div id="nav"><ul>
<li>Home</li>
<li>About</li>
<li>Products</li>
<li>Category1</li>
<li>Category2</li>
<li>Product1</li>
<li>Product2</li>
</ul></div>
But what I would REALLY like is this:
<div id="nav"><ul>
<li>Home</li>
<li>About</li>
<li>Products
<ul>
<li>Category1
<ul>
<li>Product1</li>
</ul>
</li>
<li>Category2
<ul>
<li>Product2</li>
</ul>
</li>
</ul>
</li>
</ul></div>
How can I achieve this result? I've tried many other examples, but none seems to help me. Maybe I'm not searching for the right thing.
Why to make it complicated, this could be done with a very simple recursive function.
This is what I did in my local machine. I have the connection parameter and then called a function
bulit_tree(0);
In this function it will check if the argument is 0 then select all
the item where id and parentid is same.
Then loop through and use the recursive function and generate sub tree.
Need to make sure that the $con is accesible within the function.
$con = mysql_connect("localhost","testuser","testpass");
$db_selected = mysql_select_db('testdb', $con);
if (!$db_selected) {
die ('Can\'t use testdb : ' . mysql_error());
}
bulit_tree(0);
function bulit_tree($pid=0){
global $con ;
if($pid == 0 ){
$qry = "select * from Navigation where NavigationID = ParentID";
$q = mysql_query($qry,$con);
if(mysql_num_rows($q) > 0 ){
echo '<ul>';
while($row = mysql_fetch_assoc($q)){
echo '<li>'.$row["Name"].'';
bulit_tree($row["NavigationID"]);
echo '</li>';
}
echo '</ul>';
}
}else{
$qry = "select * from Navigation where ParentID = ".$pid." AND NavigationID <> ".$pid;
$q = mysql_query($qry,$con);
if(mysql_num_rows($q) > 0 ){
echo '<ul>';
while($row = mysql_fetch_assoc($q)){
echo '<li>'.$row["Name"].'';
bulit_tree($row["NavigationID"]);
echo '</li>';
}
echo '</ul>';
}
}
}
You might need to restructure your DB first. Consider a join table. This comes handy especially if your Product falls into multiple categories.
Master table:
NavigationID Name Url
1 Home home
2 About about
3 Products products
4 Category1 #
5 Category2 #
6 Product1 #
7 Product2 #
Lookup Table:
NavigationID ParentId
1 1
2 2
3 3
4 3
5 3
6 4
7 5
Then in your class, you can make it structured like:
<?php
class Navigation{
private $menuitems;
public function __construct($par){
if(is_array($par))
$this->menuitems = $par;
}
public function __toString() {
$this->printNavigation($this->menuitems);
}
private function printMenuItem($menu) {
echo '<li>'.$menu->name.'';
if(count($menu->children)) {
print printNavigation($menu->children);
}
'</li>';
}
private function printNavigation($menuItems) {
echo "<ul>";
foreach ($menuitems as $menu {
$this->printMenuItem($menu);
}
echo "</ul>";
}
}
class MenuItem{
private $url;
private $name;
private $children;
public function __construct($par){
if(is_array($par)) {
$this->url = $par['url'];
$this->$name = $par['name'];
$this->children = $this->fetchChildren($par['NavigationID']);
}
}
function fetchChildren($id) {
$query = mysql_query("SELECT * from navigation n INNER JOIN Lookup l on l.parentID = n.NavigationID
WHERE n.NavigationID = $id") or die(mysql_error());
$num = mysql_num_rows($query);
if($num > 0) {
while($row = mysql_fetch_assoc($query)){
$this->children[] = new MenuItem($row);
}
}
}
}
$query = mysql_query("SELECT * from navigation n INNER JOIN Lookup l on l.NavigationID = n.NavigationID
WHERE l.NavigationID = l.parentIDn
AND l.NavigationID != n.NavigationID") or die(mysql_error());
$num = mysql_num_rows($query);
$menuitems = array();
while($row = mysql_fetch_assoc($query)){
$menuitems[] = new MenuItem($row);
}
$navigation = new Navigation($menuitems);
echo "<div id='nav'>$navigation</div>";
Thanx for all the comments. I've gone with Agha's suggestion of using a recursive function.
http://crisp.tweakblogs.net/blog/317/formatting-a-multi-level-menu-using-only-one-query.html

How to display child categories only last updated post?

i have categories list like
Designtype
Multi
Sub cat multi 1
sub cat multi 2
Borring
Jall
Daman
Dupatta
top parsi
Sequence
Trapping
i want to display onl last post of the jall damna dupatta and top parsi
<?php
$cat = get_categories();
echo “<pre>”;
//print_r($cat);
for each ($cat as $c)
{
if($c->cat_name == “Boring”)
{
$sub_cat = $c->term_id;
$cat2 = get_categories();
for each ($cat2 as $c2)
{
if($c2->parent == $sub_cat)
{
echo “<pre>”;
echo $c2->cat_name;
echo “<br/>”;
$aaaaaaaaaaaaaa = query_posts(array(‘category_name’ => $c2->cat_name, ‘posts_per_page’ => 1 ));
print_r($aaaaaaaaaaaaaa);
} } } }
?>

CodeIgniter: Displaying data from two tables in one loop

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

Categories