foreach loop as category with Codeigniter - php

Here is my database :
-id product prodcut-company category
-1 latitude dell laptop
-2 . acer desktop
-3 . azus mouse
-4 . sony keyboard
+If I have many product separated by category, then I want loop it by category how can I coding and show it in one page then list it as a block like laptop , desktop,...
please help !
thank you

You may create a method in the model like this-
public function getData(){
$this->db->from("product_table");
$this->db->order_by("category");
$q = $this->db->get();
if($q->num_rows() > 0){
return $q->result();
}
return [];
}
Fetch data from model using this method in the controller and pass this value to the view.
$data[
'products' => $this->your_model->getData()
];
$this->load->view('your_view',$data);
Loop these values and print in the view.
...
<?php
if(!empty($products)){
$count = count($products);
$i = 0;
while($i < $count){
$category = $products[$i]->category;
echo '<h3>Category: '.$category.'</h3>';
echo '<table>
<tr><th>Product</th><th>Company</th><th>Category</th></tr>
';
for(; $i < $count && $category == $products[$i]->category ; $i++ ){
echo '
<tr>
<td>'.$products[$i]->product.'</td>
<td>'.$products[$i]->company.'</td>
<td>'.$products[$i]->category.'</td>
</tr>
';
}
echo '</table>';
}
}
?>
...

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();
}
}

CodeIgniter function not show?

helper.website.php
public function load_top_players() {
$this->load->lib(array('rank_db', 'db'), array(HOST, USER, PASS,CHARACTERS));
$query = $this->rank_db->query('SELECT name, access FROM users ORDER BY access DESC LIMIT 5');
while($row = $query->fetch()) {
$this->rank[] = array(
'name' => htmlspecialchars($row['name']),
'level' => (int)$row['access']
);
}
return $this->rank;
}
view.header.php
<?php
$rank = load::get('website');
$i = 1;
foreach ($rank as $pos => $player) {
$first = (in_array($i, array(1))) ? '' : '';
$second = (in_array($i, array(2))) ? '' : '';
echo '<tr style="'.$first.' '.$second.' '.$third.'">
<td >'.$i.'</td>
<td>'.$player['name'].'</td>
<td>'.$player['access'].'</td>
</tr>';
$i++;
}
?>
It shows a blank page, no errors no nothing!
helper.website.php
public function getOnlineCount(){
$this->load->lib(array('rank_db', 'db'), array(HOST, USER, PASS, CHARACTERS));
return $this->registry->rank_db->snumrows('SELECT count(name) as count from users where status <> -1 AND sub_status>= 1');
}
and in in view.header.php <?php echo load::get('website')->getOnlineCount() ; ?> works perfect ! how can i transform that to my query
It's showing a blank page because you didn't pass any data to your view file. For getting data in your view file you must load a view from your controller with some data. Syntax is-
<?php
class Your_Controller_Class extends CI_Controller {
function your_function()
{
$data['data'] = 'Your data'; //get it from your model or whatever
$this->load->view('your_view_file', $data);
}
}
?>
and then access it from your view file.

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

Codeigniter/PHP How to properly use a for loop?

<?php
print_r($optimum);
$dataNumRows = count($optimum);
?>
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $cFirstName; ?>
<?php echo $cLastName; ?>
<?php endfor; ?>
My print_r inserted in my VIEW shows the following:
Array ( [cFirstName] => Array ( [0] => Tom [1] => Alexa ) [cLastName] => Array ( [0] => Jones [1] => Planter ) )
My MODEL is the following
//Get all the customers currently pending
//install for the user making the request.
function getAllCustomersPendingInstall()
{
$data=array();
//Need to use sessions to display proper
//records for each user. Temp set id to user #7
$id = 7;
//query the db and return all record where SalesRepId == $id
$query = $this->db->get_where('customers', array('SalesRepId' => $id));
//check logic, if rows exist RETURN all rows, else
//return message that no pending installs is available.
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data['cFirstName'][] = $row->customerFirstName;
$data['cLastName'] [] = $row->customerLastName;
}
} else {
$data = "No pending installs available!";
return $data;
}
//the following var_dump is only showing the last record.
//need to show all rows (which should be 2)
//var_dump($data); exit;
return $data;
}
My CONTROLLER is the following
{
$this->load->library('table');
$this->load->model('GetData');
$data['optimum'] = $this->GetData->getAllCustomersPendingInstall();
$this->load->view('welcome_message', $data);
}
And my question is how do I properly use the FOR loop in my VIEW so that I can loop through all the returned rows. As you can see the print_r is properly returning the proper rows- However I am unable to loop through them. Thanks for the help! Much appreciated!
Try this in your view:
<?php for ($i = 0; $i < $dataNumRows; $i++) : ?>
<?php echo $optimum['cFirstName'][$i]; ?>
<?php echo $optimum['cLastName'][$i]; ?>
<?php endfor; ?>
I think what you're trying to do is get an associative array for each row returned from the database. Correct me if I'm wrong about that.
Should fix your problem
$data = array();
$data_index = 0;
if($query->num_rows != 0) {
foreach($query->result() as $row) {
$data[$data_index]['cfirst'] = $row->customerFirstName;
$data[$data_index]['clast'] = $row->customerLastName;
$data_index++;
}
} else {
$data = "No pending installs available!";
return $data;
}
then in your view (where $customer is the $data array)
<?php foreach($customer as $c):?>
<?php echo $c['cfirst'];?>
<?php endforeach;?>

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