select data from seperate tables with same id - php

I have 2 tables: mb_category and mb_items, I'm trying to select items from mb_items with the same ID as the category they are assigned to in mb_category.
mb_category has 2 rows: id and category.
mb_items has 4 rows: id, item_name, item_price, and mb_category_id
What I want to do is select every item in mb_items with their corresponding category ID and echo them in the correct dropdown.
Here's what I have currently:
<ul class="nav">
<?php
$category = $db->read('mb_category', '*', '', 'ORDER BY id ASC');
// echo $category["count"] . "<br />";
// print_r($category);
foreach ($category["results"] as $row) {
?>
<li class="button-dropdown">
<a href="javascript:void(0)" class="dropdown-toggle">
<?php echo $row->category; ?> <span>▼</span>
</a>
<ul class="dropdown-menu">
<?php
$cid = $db->read('mb_category', 'id', '', '');
$item = $db->read('mb_items', '*', 'mb_category_id="$cid"', '');
// var_dump($item);
// echo $item["count"] . "<br />";
// print_r($item);
foreach ($item["results"] as $irow) {
?>
<li>
<a href="#">
<?php
echo $irow->item_name;
?>
</a>
</li>
<?php
}
?>
</ul>
</li>
<?php
}
?>
And this is my SELECT:
public function read($table_name, $cols, $where = NULL, $limit = NULL) {
//GET $cols FROM $table_name WHERE $where returns 0 for false and fetch_object() for true
$query = "SELECT " . $cols . " FROM " . $table_name;
if ($where) {
$query .= " WHERE " . $where;
}
if ($limit) {
$query .= " " . $limit;
}
//echo $query;
$sql = $this->query($query);
if ($sql) {
$data = array();
$data['count'] = $sql->num_rows;
while ($row = $sql->fetch_object()) {
$data['results'][] = $row;
}
return $data;
}
return false;
}
}

I can suggest you 2 things (I didn't test the code I'm giving you, it's just to show you the idea).
1) You are doing too many requests, you only need one :
SELECT c.id AS category_id, c.category AS category_name, i.id AS item_id, i.item_name
FROM mb_category c
LEFT JOIN mb_items i ON c.id = i.mb_category_id
2) format your data and use it to display your list :
<?php
// format data
$categories = [];
foreach ($category["results"] as $row) {
if (empty($categories[$row[category_id]])) {
$categories[$row[category_id]] = [
'id' => $row[category_id],
'name' => $row['category_name'],
'items' => [],
];
}
if (!empty($categories[$row[item_id]])) {
$categories[$row[category_id]]['items'][] = [
'id' => $row['item_id'],
'name' => $row['item_name'],
];
}
}
?>
<ul class="nav">
<?php
// display data
foreach ($categories as $categoryId => $category) {
?>
<li class="button-dropdown">
<a href="javascript:void(0)" class="dropdown-toggle">
<?php echo $category['name']; ?> <span>▼</span>
</a>
<ul class="dropdown-menu">
<?php foreach ($category['items'] as $item) { ?>
<li>
<a href="#">
<?php
echo $item['name'];
?>
</a>
</li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>

Related

How to add active class in dynamic menu list in codeigniter?

I want to display <li class = "active"> in my current URL when I click any menu.
Here is what I have tried:
<?php
$uri_string = $this->uri->uri_string();
$id_user = $usr->id;
$get_group = $this->db->get_where('users_groups', array('user_id'=> $id_user));
$hasil = $get_group->result();
foreach($hasil as $h)
if(isset($h->group_id)){
$in_group = $this->ion_auth->in_group($h->group_id);
if(isset($in_group)){
$get_menu = $this->db->get_where('menu',array('parent_menu' => 0, 'menu_users_groups' => $h->group_id));
$menu = $get_menu->result();
foreach($menu as $m){
$cekSub = $this->db->get_where('menu',array('parent_menu' => $m->id));
if($cekSub->num_rows() > 0){
echo '<li>';
echo '
<a href="javascript:void(0);" class="menu-toggle">
<i class="material-icons">'.$m->icon.'</i> <span>'.$m->menu_name.'</span>
</a>
<ul class="ml-menu">
<li>';
foreach($cekSub->result() as $c)
echo anchor(''.$c->controller_link.'','<i class="material-icons">'.$c->icon.'</i><span> '.$c->menu_name.'</span>');
echo '</li>
</ul>
</li>';
} else {
echo '<li>';
echo anchor(''.$m->controller_link.'','<i class="material-icons">'.$m->icon.'</i><span> '.$m->menu_name.'</span>');
echo '</li>';
}
}
}
}
?>
The problem is, that if not in the curent URL class, active is hidden - just <li> is displayed.
How to fix this?
it's solved with :
<?php
$getUri = $this->uri->uri_string();
$id_user = $usr->id;
$get_group = $this->db->get_where('users_groups', array('user_id'=> $id_user));
$hasil = $get_group->result();
foreach($hasil as $h)
if(isset($h->group_id)){
$in_group = $this->ion_auth->in_group($h->group_id);
if(isset($in_group)){
$get_menu = $this->db->get_where('menu',array('parent_menu' => 0, 'menu_users_groups' => $h->group_id));
$menu = $get_menu->result();
foreach($menu as $m){
$cekSub = $this->db->get_where('menu',array('parent_menu' => $m->id));
$getSub = $cekSub->result();
if($cekSub->num_rows() > 0){
echo '<li';
foreach($getSub as $c)
if($c->controller_link==$getUri){echo ' class="active"';}
echo '>
<a href="javascript:void(0);" class="menu-toggle">
<i class="material-icons">'.$m->icon.'</i> <span>'.$m->menu_name.'</span>
</a>
<ul class="ml-menu">
<li>';
foreach($getSub as $c)
echo anchor(''.$c->controller_link.'','<i class="material-icons">'.$c->icon.'</i><span> '.$c->menu_name.'</span>');
echo '</li>
</ul>
</li>';
} else {
echo '<li';
if($m->controller_link==$getUri){echo ' class="active"';}
echo '>';
echo anchor(''.$m->controller_link.'','<i class="material-icons">'.$m->icon.'</i><span> '.$m->menu_name.'</span>');
echo '</li>';
}
}
}
}
?>

Adding categories & subcategories to a blog

Ok, I have done lots of research and looked at lots of stackoverflow questions but none have answered my question.
I'm building a simple blog and am at the moment i'm trying to build a simple categories/subcategories system but have hit an obstacle in making the subcategories load under their parent. If you know an easier method to the one i am doing below please let me know.
Here is how my db is structured:
id || name || parent_id || status
------------------------------------------
1 || category1 || NULL || 1
2 || subcategory1 || 1 || 1
Then i have my model code:
public function getCategories()
{
$results = $this->db->select('msi_items_categories','status = 1 AND parent_id = NULL');
if( !is_array($results[0]) ) {
$new_results = array();
array_push($new_results, $results);
return $new_results;
} else {
return $results;
}
}
public function getSubCategories($parent)
{
$bind = [':parent' => $parent];
$results = $this->db->select('msi_items_categories','status = 1 AND parent_id = :parent');
if( !is_array($results[0]) ) {
$new_results = array();
array_push($new_results, $results);
return $new_results;
} else {
return $results;
}
}
This is my controller code:
public function error()
{
$getSettings = $this->setting->getAll();
$getCategories = $this->setting->getCategories();
$getSubCategories = $this->setting->getSubCategories();
if(is_array($getCategories[0]) ) {
$isCategory = true;
} else {
$isCategory = false;
}
if(is_array($getSubCategories[0]) ) {
$isSubCategory = true;
} else {
$isSubCategory = false;
}
$data = [
'settings' => $getSettings,
'mainCategory' => $getCategories,
'subCategory' => $getSubCategories,
'isCategory' => $isCategory
'isSubCategory' => $isSubCategory
];
$this->view('index', $data);
}
Then I have my templatecode which is where im trying to do the foreach and the top category works fine but i just can't figure out how i do the subcategories. Before i started using the MVC model, i would simply just put the class inside the main category foreach and then put the id but now its all done in the controller so i cannot figure out how i do subcategories using the MVC model.
<?php foreach($data['mainCategory'] as $category) : ?>
<li class="dropdown">
<a class="dropdown-toggle nav-link dropdown-toggle pl-0" data-toggle="dropdown" aria-expanded="false" href="#"><?php echo $category['name']; ?></a>
<div class="dropdown-menu" role="menu">
<a class="dropdown-item" role="presentation" href="#"><i class="text-black-50 fas fa-box"></i> All <?php echo $category['name']; ?></a>
<div class="dropdown-divider" role="presentation"></div>
<?php foreach($data['subCategory'] as $scategory) : ?>
<a class="dropdown-item" role="presentation" href="#"><i class="text-black-50 <?php echo $scategory['icon']; ?>"></i> <?php echo $scategory['name']; ?></a>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
Thanks very much!
$query = 'SELECT id, parent_id, name, icon FROM categories ORDER BY name';
$result = mysqli_query($conn, $query) OR trigger_error($query.'<br>'.mysqli_error($conn),E_USER_ERROR);
$refs = Array();
$categories = Array();
while($row = mysqli_fetch_assoc($result))
{
$thisref = &$refs[$row['id']];
$thisref['name'] = $row['name'];
$thisref['icon'] = $row['icon'];
if($row['parent_id']) $refs[$row['parent_id']]['children'][$row['id']] = &$thisref;
else $categories[$row['id']] = &$thisref;
}
echo '<ul class="nav navbar-nav mr-auto">';
foreach($categories as $category)
{
echo '<li class="dropdown">';
echo is_array($category['children'])
? '<a class="dropdown-toggle nav-link dropdown-toggle pl-0" data-toggle="dropdown" aria-expanded="false" href="#">'.$category['name'].'</a>'.sub($category['children'])
: $category['name'];
echo '</li>';
}
echo '</ul>';
function sub(&$subCat)
{
echo '<div class="dropdown-menu" role="menu">
<a class="dropdown-item hide-me" role="presentation" href="#"><i class="fas fa-fire mr-2"></i> Most Popular </a>
<div class="dropdown-divider hide-me" role="presentation"></div>';
foreach($subCat as $id => $subcategory)
{
echo '<a class="dropdown-item" role="presentation" href="'.FULL_ROOT.'/category/'.$id.'/"><i class="'.$subcategory['icon'].' mr-2"></i>'.$subcategory['name'].'</a>';
}
echo '</div>';
}

Selected category doesn't remain active after clicking

I have a website which is showing products online. In it, I have categories and subcategories listed. When I'm clicking on a category, it doesn't remain active/selected. I have a class="active" which is added to the selected category when clicked but it doesn't expand on selection.
This is my website www.sitimobil.mk. The example site is www.fixit.mk
On the left side you have the categories and subcategories.
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)) {
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?= $emrikategorise; ?>
<ul <?php
if ($_GET['kid'] == $idkategori) {
echo 'class="active"';
}
?>>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '" . $idkategori . "'");
$rPrind = mysqli_query($dbc, $qPrind);
while ($prind = mysqli_fetch_array($rPrind)) {
?>
<li><a href="kategori.php?kid=<?= $prind['kid'] ?>&kprind=<?= $prind['kprind'] ?>" <?php
if ($_GET['kid'] == 48) {
echo 'class="active"';
}
?>><?= $prind['kemri'] ?></a></li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php
}
mysqli_free_result($rKategori);
}
?>

display sub-menu of parent menu from parent id php

<?php
$page= $objPage-> get_page();
$id = isset($_GET['id']);
$child= $objPage-> get_child_page($id);
?>
<ul class="nav nav-tabs">
<li role="presentation" class="dropdown">
<?php
while($row = mysql_fetch_array($page) ) { ?>
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria- expanded="false">
<?php echo $row['title']; ?> <span class="caret"></span>
</a>
<?php } ?>
</li>
</ul>
Function get_page:
function get_page($id="") {
$sql = "SELECT "; if( !empty($field) ){
$sql .=" title FROM page WHERE page_id>1 " ;
} else {
$sql .= " * FROM page ";
}
if( !empty($id) ){
$sql .=" WHERE page_id=".$id;
} else {
$sql .=" WHERE parent_id= -1";
}
$result = mysql_query($sql) or die( mysql_error() );
if( !empty($id) && $result ){
$value = mysql_fetch_array($result) ;
return $value;
}
return $result;
}
Function get_child_page:
function get_child_page($id){
$sql = "SELECT * FROM page WHERE parent_id= $id";
$result = mysql_query($sql);
return $result;
}
i got the parent menu which has the parent id -1 but i want to display the child menu from parent id .. any solution ??

Echo results of mysql query with php

I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the results within a unordered list using a while loop like this
<ul>
<?php {do { ?>
<li><?php echo $row_people['name'];?></li>
<?php } while ($row_people = mysql_fetch_assoc($people));}?>
</ul>
But I can't used this as my html does not allow it.
<ul>
<li class="first">
Kate
<li>
<li class="second">
<img src="john.jpg" />John
<li>
<li class="third">
<span>Max</span>
<li>
</ul>
My question is how can echo the name that was retrieved from the database into the appropriate place within this html?
Thanks for your help.
Try this:
<?php
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
if(mysql_num_rows($people) > 0){
?>
<ul>
<?php
while ($row_people = mysql_fetch_assoc($people)){
?>
<li><?php echo htmlentities($row_people['name']);?></li>
<?php
}
?>
</ul>
<?php
}
?>
You'll just have to create a renderer for each "type" of user (assuming you have a type property on the user rows) or based on their attributes. For example, let's say you're going to have to filter based on the attributes:
<?php
function render_simple($person) {
return '' . $person['name'] . '';
}
function render_with_image($person) {
return '<img src="' . $person['image'] . '.jpg"/>' . $person['name'] . '';
}
function render_special($person) {
return '<span>' . $person['name'] . '</span>';
}
function render_person($person) {
if ($person['image']) {
return render_with_image($person);
}
if ($person['special']) {
return render_special($person);
}
return render_simple($person);
}
$i = 0;
while ($row_people = mysql_fetch_assoc($people)){ ?>
<li class="index<?php echo ++$i; ?>">
<?php echo render_person($person); ?>
</li>
<?php
}
?>
This should work, with the exception that instead of class names first, second, etc, you'll now have index1, index2, etc.

Categories