Bootstrap multi-level drop down not working - php

I am working on a PHP website. And for some reasons, I need to add multiple level dropdown in my navigation bar. I tried the bootstrap class="dropdown-submenu" but I don't know why it has not worked.
<ul class="dropdown-menu">
<?php
$alllinks = mysql_query("SELECT `cid`, `cname` FROM `services` WHERE `parentid`=0");
while($reslink = mysql_fetch_assoc($alllinks)){ ?>
<li class="dropdown-submenu">
<a tabindex="-1" href="<?php echo MYWEBSITE;?>services/<?php echo to_prety_url($reslink['cname']).'-'.$reslink['cid'];?>.html">
<?php echo $reslink['cname'];?>
</a>
<ul class="dropdown-menu">
<li>
<a href="<?php echo MYWEBSITE;?>servicedetail/<?php echo to_prety_url($rowsb['cname']).'-'.$rowsb['cid'];?>.html">
<?php echo $rowsb['cname'];?>
</a>
</li><br>
</ul>
</li><br>
<?php } ?>
</li>
</ul>

Throughout your code You haven't enclosed MYWEBSITE in inverted comma's
you have written.
<?php echo MYWEBSITE;?>
whereas you should write
<?php echo "MYWEBSITE";?>
and You are using the old and Deprecated mysql connector it is higly recommended that you switch to PDO or mysqli.

Related

How I can make drop down menu from my categories mysql table only show if parent_id is not 0

So hey there as the title said I am looking for away to make my categories with subcategories. I been looking in stackoverflow for what I need but none has help me of the examples..
Here is how my table look like
So I know what I want and what I need but I have no idea how I can do that possible
I have to SELECT * FROM categories ORDER by position ASC
I have to check if parent_id is bigger then 0.
I have to remove the parent_id from my navbar and show them only under the category name where it should be by dropdown menu .
But I have no idea how I could do all of that ..
Here is how I am selecting only my categories and display them
$catsq = mysqli_query($con,"SELECT * FROM categories ORDER by position ASC");
while($catinfo=mysqli_fetch_assoc($catsq)) {
echo '
<li class="nav-item'.(isset($_GET["cat"]) && $_GET["cat"]==$catinfo["id"] ? " active" : "").'">
<a class="nav-link" href="./index.php?cat='.$catinfo["id"].'">'.$catinfo["name"].'</a>
</li>
';
}
and it's look like this
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="cat=1">TestCat</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cat=2">TestCat2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cat=3">TestSub</a>
</li>
</ul>
but I want It to look like this
<ul class="nav navbar-nav">
<li class="">TestCat</li>
<li class="dropdown ">
//TestCat2 have to doing nothing always.
TestCat2</i>
<ul class="dropdown-menu">
<li><a class="nav-link" href="cat=3">TestSub</a></li>
</ul>
</li>
</ul>
when the parent_id is more then 0..
If anyone can help me with this would be great..
Thanks to everybody.
There are several approaches you can take:
Build an array
Nested queries
Recursion
Array
This approach builds a data structure that you can iterate through in your view. Working example
<?php
// get db connection...
// create categories array
$stmt = mysqli_query($con, "SELECT * FROM categories ORDER BY position ASC");
while( $row = mysqli_fetch_assoc($stmt)) {
// $category[ $row['parent_id] ][ $row['id'] ] = $row; // use if you need to access other fields in addition to name
$category[ $row['parent_id] ][ $row['id'] ] = $row['name'];
}
// other php stuff...
?>
<html>
... snip ...
<ul class="nav navbar-nav">
<?php foreach($category[0] as $id => $name): ?>
<?php if( isset( $category[$id]) ): ?>
<li class="dropdown ">
<?= $name ?>
<ul class="dropdown-menu">
<?php foreach($category[$id] as $sub_id => $sub_name): ?>
<li><a class="nav-link" href="?cat=<?= $sub_id ?>" ><?= $sub_name ?></a></li>
<?php endforeach; ?>
</ul>
</li>
<?php else: ?>
<li class="">
<?= $name ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Nested Queries
This method is easiest to display using an imaginary class that does all the sql stuff behind the scenes. For the sake of argument, we will assume a class Category that has a method named listByParent($parent_id) which returns a list of rows having the designated parent_id.
<?php
$cat = new Category();
$topLevel = $cat->listByParent(0);
?>
<html>
... snip ...
<ul class="nav navbar-nav">
<?php foreach( $topLevel as $topRow ): ?>
<!-- note, this method is run on every iteration of top level categories -->
<?php $subRows = $cat->listByParent($topRow['id']) ?>
<?php if( count($subRows)): ?>
<li class="dropdown ">
<?= $topRow['name'] ?>
<ul class="dropdown-menu">
<?php foreach($subRows as $row): ?>
<li><a class="nav-link" href="?cat=<?= $row['id'] ?>" ><?= $row['name'] ?></a></li>
<?php endforeach; ?>
</ul>
</li>
<?php else: ?>
<li class="">
<?= $topRow['name'] ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Recursion
Using recursion would allow you to have “unlimited” levels of subcategories. However, it’s a level of complexity that does not seem warranted in this case. But should you want to pursue it, note that the best way to approach it would be to make a template for the html that could be accessed programatically, with $cat->findByParent() being a key player...

Bootstrap drop-down menu using PHP and MySQL

I am new to PHP. With Laravel this is simple:
#isset($tags)
#foreach($tags as $tag)
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
{{ $tag->name }}
</a>
<ul class="dropdown-menu">
#foreach($tag->categories as $category)
<li><a href="{{-- route('register') --}}" {{$category->name }}</a></li>
<li class="divider"></li>
#endforeach
</ul>
</li>
#endforeach
#endisset
I need to use plain PHP as Laravel seems to slow considerably and I did this
<?php if(isset($tags)): ?>
<?php foreach($tags as $tag): ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
<?php echo $tag['name'] ?>
</a>
</li>
<?php endforeach ?>
Now I am stuck.
The $tags display quite alright but I don't seem to get $tag->categories to dropdown.
this how my query looks like:
SELECT t.id, t.name as tag_name, c.id, c.name as c_name from tags t INNER JOIN category_tag ct ON (t.id = ct.tag_id)'.
'INNER JOIN categories c ON (ct.category_id = c.id) ORDER BY t.id
Any help would be nice.
Try this:
<?php
if(isset($tags)){
foreach($tags as $tag){ ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
<?php echo $tag->name; ?>
</a>
<ul class="dropdown-menu">
<?php
foreach($tag->categories as $category){ ?>
<li><a href="{{route('register')}}" <?php echo $category->name; ?> </a></li>
<li class="divider"></li>
<?php } ?>
</ul>
</li>
<?php }
}
?>
Although, i would recommend using laravel syntax. it wont make your page slower because the are just helpers that are translated to something like the above example.
No dropdown seems normal, cause you don't have <ul class="dropdown-menu"> in your php script, like the one mentioned in your laravel blade:
<ul class="dropdown-menu">
#foreach($tag->categories as $category)
<li><a href="{{-- route('register') --}}" {{$category->name }}</a></li>
<li class="divider"></li>
#endforeach
</ul>
However, as you said, in laravel it is simple, cause of Eloquent Model relationships.
Of course, you can do it, in vanilla php in many different ways.
These 2 approaches came up my mind...
Fetch categories in second query and align them to your $tag in foreach.
Rebuild your query and add sub queries, to add concatenated column, which can be parsed by php.
Please note that, the first one uses more php processing, whilest the second one, causes much more load on database.
Let's focus on the second one, with mixed database processing and php...
So lets modify your query to:
SELECT t.id, t.name as tag_name,
(SELECT group_concat(
(SELECT concat_ws(':',c.id,c.name) FROM categories c WHERE ct.category_id = c.id)
) FROM category_tag ct WHERE ct.tag_id = t.id) as categories_ctn
from tags t ORDER BY t.id
Now you will have a column categories_ctnwith concatenated data separated by , with category_id:category_name
So the last thing to do, is to explode your data to arrays and modify your view script. Please note comments in this php script...
<?php if(isset($tags)): ?>
<?php foreach($tags as $tag) { ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
<?php echo $tag['tag_name'] ?>
</a>
<ul class="dropdown-menu">
<?php
$categories = explode(',',$tag['categories_ctn']);
foreach($categories as $category_data) {
$category = explode(':',$category_data);
?>
<li><a href="#<?php echo $category[0]; // here you get category id ?>" <?php echo $category[1]; // here you get category name ?></a></li>
<li class="divider"></li>
<?php } ?>
</ul>
</li>
<?php } ?>
I hope that now you have a grasp, of what you can receive from mysql query, and what you can do with that data in php.
I have not tested the code, but it should work straight away.
Thoughtful thought, do you use Laravel or not?
Cause in Laravel all mentioned above is pointless, and you can achieve the same result really simple, via Model relationships, like in the blade you mentioned...
The code mentioned above is portable, meaning you can use it in any php project, and I believe this is what your question was...
Second thought...
Remember that joining categories in mysql, will bring you one of categories instead of all...
This example is about showing all categories for tag in your menu...
And finally don't avoid Laravel, cause it is beauty one of a kind... :)

making class="active" for nav menu in php

I'm creating a website..When it comes to the navigation menu, I listed it and need the nav bar class to be active when that menu is clicked. It's fine to give class="active" for the list tag. But I need it to be active only when clicked. How can I achieve this .?
My list is :
<div class="menu">
<ul class="nav" id="nav">
<li class="active">
<?php echo anchor("cntrl/index","Home"); ?>
</li>
<li><?php echo $this->session->userdata('user_name'); ?></li>
<li>About</li>
<li>
<?php echo anchor("cntrl/jobs","Jobs"); ?>
</li>
<li>
<?php echo anchor('cntrl/logout','Logout'); ?>
</li>
<div class="clearfix"></div>
</ul>
<script type="text/javascript" src="<?php echo base_url(); ?>/js/responsive-nav.js"></script>
</div>
Well, I handle this sort of issue as follows:
set the active link (which is resided in the url when the link is clicked) into an variable in the controller function which is called by the link
$data['active_link'] = 'home'; # for example
check it in the view file (JS):
$(document).ready(function(){
var active_link = "<?php echo $active_link;?>";
$("li").removeClass('active');
$("#"+active_link).addClass('active');
});
Use the following code.
<li class="<?php echo (endsWith($_SERVER['REQUEST_URI'], 'cntrl/jobs')? 'active':''); ?>">
<?php echo anchor("cntrl/jobs","Jobs"); ?>
</li>
Main part of this code is
endsWith($_SERVER['REQUEST_URI'], 'cntrl/jobs')
Where $_SERVER['REQUEST_URI'] is your current URL. and 'cntrl/jobs' is your menu which is being checked with current URL.

highlight currently menu selection php

I have PHP code which will check if the user is logged in and will return the menu if they are, however I was wondering if there was a way to make each of the current selected highlighted or would I have to go through and add them as a manual list to each page?
The code is:
<?php
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Links for logged in user
if(isUserLoggedIn()) {
echo "<div id='Default'>
<ul>
<li><a href='/account.php' >Account Home</a></li>
<li><a href='/user_settings.php' >User Settings</a></li>
<li><a href='/logout.php' >Logout</a></li>
</ul></div>
<div id='button1'>
<a href='/Demos.php'>Demos</a></div>
<div id='button2'>
<a href='/Helpfiles.php'>Helpfiles</a></div>
<div id='greeting'>
Hello, $loggedInUser->displayname.</br>";
}
//Links for users not logged in
else{
echo "<div id='Default'>
<ul>
<li><a href='/login.php'>Login</a></li>
<li><a href='/register.php'>Register</a></li>
<li><a href='/forgot-password.php'>Forgot Password</a></li>";
echo "</ul></div>";
}
?>
Now I know that on a normal CSS one it would just be .current and you can do it that way, however I cannot make that work with this echo because they are all on the screen at the same time. What would be the best way? Manually add would see like the longer way.
p.s. this is used in conjunction with usercake
You don't need to put HTML into an echo in PHP. I would recommend something like this.
So you will end up with something like:
<?php
if(isUserLoggedIn()) {
?>
<div id='Default'>
<ul>
<li><a href='/account.php' >Account Home</a></li>
<li><a href='/user_settings.php' >User Settings</a></li>
<li><a href='/logout.php' >Logout</a></li>
</ul>
</div>
<div id='greeting'>
Hello, <?php echo $loggedInUser->displayname; ?>
</br>
<?php } ?>
Then I would not recommend you to add the class with PHP because you will suffer from lisibility with a lots of if and else cases.
The best way to do this would be to use ID/Classes for your LIs and add the selected class to a specitic item with a simple JavaScript function.
Btw, if you really feel the needs to have this in PHP I recommend you to read this:
http://www.catswhocode.com/blog/snippets/highlight-current-menu-item-in-php
http://webdeveloperswall.com/php/how-to-highlight-the-current-page-in-menu-in-php
So you will have something like:
<?php if(isUserLoggedIn()) { ?>
<ul>
<?php
$url = $_SERVER['REQUEST_URI'];
$parts = parse_url($url);
$page_name = basename($parts['path']);
?>
<li><a class="<?php echo ($page_name=='acount.php')?'selected':'';?>" href="where-to-buy.php">WHERE TO BUY</a></li>
<li><a class="<?php echo ($page_name=='user_settings.php')?'selected':'';?>" href="about.php">ABOUT US</a></li>
<li><a class="<?php echo ($page_name=='logout.php')?'selected':'';?>" href="contact.php">CONTACT US</a></li>
</ul>
<?php } ?>
EDIT
Finally, you should end up with something like this: http://pastebin.com/V8jxwi7T
You could grab the page you are currently browsing and see if it matches. Something like this perhaps? (sorry for the crude example)
<?php
// will return 'home' is the filename is home.php
$filename = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
?>
<li <?php if ($filename == "home") { echo "class='active'"; } ?>>
Home
</li>
Some info on pathinfo and how it works here
Just add class to selected <li> element, this way:
echo "<div id='Default'>
<ul>
<li><a href='/account.php' >Account Home</a></li>
<li class="selected"><a href='/user_settings.php' >User Settings</a></li>
<li><a href='/logout.php' >Logout</a></li>
</ul></div>";
In your CSS, put appropriate style for .selected class.
You should have a variable telling in which page you are, let's say it's $currentpage.
echo "<div id='Default'>
<ul>
<li".($currentpage=='account' ? ' class="selected"' : '')."><a href='/account.php' >Account Home</a></li>
<li".($currentpage=='usersettings' ? ' class="selected"' : '')."><a href='/user_settings.php' >User Settings</a></li>
<li><a href='/logout.php' >Logout</a></li>
</ul></div>";

html quotations mix up with php

I got some html code
<?php
if($loggedIn){
echo "<div id='navigation'>
<ul>
<li>
<a href='javascript:toggleLayer('video');'>Global</a>
</li>
<li>
<a href='javascript:toggleLayer('info');'>About</a>
</li>
<li>
<a href='javascript:toggleLayer('register_main');'>Join!</a>
</li>
</ul>
</div>"};
But when I click on the url's on the website, they happen not to execute the javascript code.
after inspectiong one of the elements I found out that
<a video');'="" href="javascript:toggleLayer(">Global</a>
is the code generated, which is wrong ofcourse.
My only clue would be that it should be
Global
Though i have no clue how to fix that inside the echo, because it has to be in between the if-statement
Thanks in advance!
Replace:
<?php if($loggedIn){
echo "<div id='navigation'>
<ul>
<li>
<a href='javascript:toggleLayer('video');'>Global</a>
</li>
<li>
<a href='javascript:toggleLayer('info');'>About</a>
</li>
<li>
<a href='javascript:toggleLayer('register_main');'>Join!</a>
</li>
</ul>
</div>"}; ?>
with:
<?php if($loggedIn){ ?>
<div id="navigation">
<ul>
<li>
Global
</li>
<li>
About
</li>
<li>
Join!
</li>
</ul>
</div>
<?php } ?>
When using quotes inside of strings " I said "Hello" ". You need to escape the matching surrounding quotes like: " I said \"Hello\" ".
Try this
...
<a href='javascript:toggleLayer(\"video\");'>Global</a>
...
The problem are your quotation marks.
You have to escape the ones inside the <a> tags where you set the params for your javascript function e.g. 'video'

Categories