I am trying to build a menu with an active page element for CSS using PHP and MySQL.
This example PHP/HTML hybrid works, and is what I'm trying to mimic.
<nav><ul>
<li<?php if ($thisPage == "1") echo " class=\"active\""; ?>>page 1</li>
<li<?php if ($thisPage == "2") echo " class=\"active\""; ?>>page 2</li>
<li<?php if ($thisPage == "3") echo " class=\"active\""; ?>>page 3</li>
</nav></ul>
I want to blend this statement to set the active class:
<?php if ($thisPage == $menuID) echo " class=\"active\""; ?>
Into this unordered list statement
<?php
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
?>
This is where I am but I can't seem to get the syntax to work correctly.
echo "<li" . "if(" . $thisPage==$menuID . ")". echo ' class=\"active\"';" . ">" . "" . $row_rsMenu['menuName'] . "</li>\n";
If someone could help me to understand where this went wrong I'd appreciate it.
You have your if statement encapsulated in quotes. That means that PHP won't interpret it. Instead, it will print it out along with your HTML.
Something along the lines of this will work better:
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
$active = ""; //not active by default
if($thisPage==$menuID){
$active = ' class="active" ';
}
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
By the way, where are you getting $menuID from?
Your error is wrapping the if block within quotes, among a few other issues with quotes.
Try this instead:
echo '<li', (($thisPage==$menuId) ? ' class="active"' : ''), '>', '', $row_rsMenu['menuName'], '</li>';
This uses a ternary operator to shorten things up a bit, in addition to fixing your syntax error.
Related
I'd like to add an active class with PHP instead of using javascript.
But I probably broke the code somewhere.
I'm using bootstrap.js version 3 and I'm building my tabs using PHP because I need to use my tabs on the control panel in my app.
So essentially I didn't add any javascript or jquery so far, I'm just using the native functions for tabs in bootstrap.js (and jquery):
<?php foreach ($database as $item): ?>
<?php
if (isset($item['associations'])) {
foreach ($item['associations'] as $value) {
echo "<div class='modal' id='des_" . $value['des_id'] . "'>";
echo "<div class='modal-sandbox'></div>";
echo "<div class='modal-box'>";
echo "<div class='modal-body'>";
echo "<div class='close-modal'>✖</div>";
echo "<h3>Credit and values</h3>";
echo "<h5>" . $value["designation_name"] . " - Credit: " . $value["designation_credits"] . "</h5>";
echo "<ul class='nav nav-pills'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
$first_element = reset($value["credits"]);
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<li class='active'><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
} else {
echo "<li><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
}
}
}
}
echo "</ul>";
echo "<div class='tab-content clearfix'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<div class='tab-pane active' id='tab_" . $credits[4] . "'>";
} else {
echo "<div class='tab-pane' id='tab_" . $credits[4] . "'>";
}
echo "<div class='single-credit'>";
?>
<?=form_open();?>
<?php
echo "<input type='hidden' name='id' value='" . $credits[4] . "'>";
echo "<div>Identifier: <span>" . $credits[0] . "</span></div>";
echo "<input name='edit_credits' type='submit' value='Edit' class='submit'>";
echo "</div>";
echo "</div>";
echo "</div>";
?>
<?=form_close()?>
<?php
}
}
}
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?>
<?php endforeach;?>
To explain my code I will start from the list:
Since it's a really complex array, I'm taking the first element with the reset function to add the active class only on that very element.
Then I added the href element to point to the id of the matching div later on, and then I close my list.
Later on, I create another loop and I use the id to match both the list and the div and I used the trick that I used before to add the class active only on my first element of my array.
Everything works except for the fact that, if I click another element of the list, the matching div won't work, the very first element of the array will keep the class active, so I can't switch beteween element.
I need to spot the error.
UPDATE:
The problem that I have with jquery, in this case, is that if I use a toogleClass for example like that:
$(".nav-pills li").click(function(e) {
e.preventDefault();
tab = $(this).find('a').attr('href');
$("#" + tab).toggleClass('active');
});
It won't be able to toggle properly the class on the first element, that one to which I added the class active with php.
I think you miss to change the URL when click it, in the backend (PHP) you need to know where the user is, so, you check the "parameter" and mark active or not the current tab.
For example:
printf("<div class='tab-pane %s' id='...'>", $credits[4] == $_GET['tab'] ? 'active':'');
I need some assistance to create a foreach loop which will display each array item from an array with three items. Currently, my code correctly displays the first and last item; however, it does not display the second item.
The loop will be used to generate a navbar from the items in the array.
Here is my PHP code:
<ul>
<?php
$navOptions = array('home','services','contact');
foreach($navOptions AS $navOption) {
if ($navOption == $currentPage) {
echo '<li>' . ucfirst($navOption) . '</li>';
} else {
echo '<li><a href="' . $navOption . '.php>' . ucfirst($navOption) . '</li></a';
}
}
?>
</ul>
This code generates a list of links like this:
Home
Contact
However, it does not generate the "Services" list item.
A side note: the $currentPage variable is declared as a global variable on each individual html page ie, within index.php, services.php, contact.php.
You are missing some double quotes, and the closing > of the else statement, should be as follows:
$navOptions = array('home','services','contact');
foreach($navOptions AS $navOption) {
if ($navOption == $currentPage) {
echo '<li>' . ucfirst($navOption) . '</li>';
} else {
echo '<li>' . ucfirst($navOption) . '</li>';
}
}
I'm creating a Dynamic Navigation using PHP, and i want to insert a php code inside a php code
on an <li>, i want to insert this line of code inside a list item
<?php printf('<li' if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="current"';>); printf('%s %s </a></li> ', $row['name'],$row['DESCRIPTION']); } ?>
Wouldn't be better this way (?):
$content = "<li ";
if (strpos($_SERVER['PHP_SELF'], 'index.php')){
$content .= "class='current'";
}
$content .= "> </a></li>" . $row['name'] . " " . $row['description'];
Try this way:
<?php
$index = ((strpos($_SERVER['PHP_SELF'], 'index.php')) ? true : false);
printf('<li' . (($index) ? 'class="current"' : '' ) . '%s %s </a></li> ', $row['name'],$row['DESCRIPTION']);
?>
<?php
printf('<li' . (strpos($_SERVER['PHP_SELF'], 'index.php')) ? 'class="current"' : '' . '>');
printf('%s %s </a></li> ', $row['name'], $row['DESCRIPTION']);
?>
$is_current = '';
if(strpos($_SERVER['PHP_SELF'], 'index.php')){ $is_current = 'class="current"'; }
printf('<li'.$is_current.'>%s %s </a></li>', $row['name'],$row['DESCRIPTION']);
Not totally clear what you are asking, but I guess you can get what you want writing it differently, e.g.
<?php
echo "<li ";
if (strpos($_SERVER['PHP_SELF'], 'index.php')) {
echo ' class="current"';
}
// missing: '><a ...>'
printf(' %s %s </a></li> ', $row['name'], $row['DESCRIPTION']);
?>
(there's a final } without an opening {, I've just stripped it, without asking myself if it had to be the closing } of the missing opening { of the if).
Or you can use the ?: operator.
For good pratices and best identification in your code, try this:
if (strpos($_SERVER['PHP_SELF'], 'index.php')){
$class = "";
}else{
$class = "current";
}
printf('<li class="current"> %s %s </a></li>', $row['name'], $row['DESCRIPTION']);
I am trying to have set the position of my li element according to the value of the variable that I will be displaying. For some reason this doesn't seem to be working. Does anyone see anything wrong with my code? Thanks
echo "<li class=\"compensation_post posts_values\" if($compensation == \"Free\") {style=\"left: 540px;\"}>$compensation</li>";
PHP can parse variables in a double-quoted string, but not conditions. So you're going to need to break this out in one of two ways:
Separated:
$style = '';
if ($compensation == "Free")
$style = " style=\"left:540px;\"";
echo "<li class=\"compensation_post posts_values\"$style>$compensation</li>";
Or in-line:
echo "<li class=\"compensation_post posts_values\" "
. ($compensation == "Free" ? "style=\"left:540px;" : "")
. ">$compensation</li>";
I suppose you can also go in and out of php code like:
?><li class=\"compensation_post posts_values\" <?= ($compensation == "Free" ? "style=\"left:540px;\"" : ""); ?>>$compensation</li>
You cannot use an if statement like that. Instead, you could use a shorthand if. Something like this should work:
echo "<li class=\"compensation_post posts_values\"" . (($compensation == 'Free') ? 'style=\"left: 540px;\" : '') . ">$compensation</li>";
Or, you could do like this:
if ($compensation == 'Free')
$style = 'style="left: 540px;"';
echo "<li class=\"compensation_post posts_values\" $style>$compensation</li>";
I've setup a menu for a fairly simple site based on icant.co.uk. It's fairly simple with maybe 5 pages. The small site is mainly a mysql browser for a few tables using MATE. Theres a common.php file that contains the header & footer HTML so thats where I put the code below.
The code below highlights the current page on the menu. Its ugly and I'm sure there has to be a better way to do it.
Any help is appreciated, thank you!
heres my code
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
if ($currentFile == "orders.php"){
echo '<li id="active">Orders</li>';
}
else{
echo '<li>Orders</li>';
}
if ($currentFile == "customers.php"){
echo '<li id="active">Customer List</li>';
}
else{
echo '<li>Customer List</li>';
}
if ($currentFile == "order_details.php"){
echo '<li id="active">Order Details</li>';
}
else{
echo '<li>Order Details</li>';
}
?>
UPDATE For those curious, below is the working code!
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "order_details.php", "title" => "Order Details"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$currentAppend = ($page['file'] == $currentFile) ? ' id="current' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
?>
What I normally do is something like (for all elements...):
<li class="<?php if (condition) echo 'selected'; ?>">content part, links, etc.</li>
Not sure if that's what you meant, but this way you'll get rid of this ugly if-else:
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
A more concise way of doing it (if you have short tags enabled) would be:
<li class="<?= $test=="your_page_name" ? 'selected' : 'not_selected'?>">Link Name</li>
It performs the same function as the first answer, just more concisely.
Here's a snippet from a project of mine. It it old ugly code, and uses tables, but you can just as easily use the idea for divs and cleaner markup. The trick is to make the navigation use a different class if the current page matches it's url.
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_home.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_home.php'>Billing Home</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_schedules.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_schedules.php'>Billing Schedules</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_outstanding.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_outstanding.php'>Outstanding</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_list.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_list.php'>List All</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_history.php'>Billing History</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_statement_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_statement_history.php'>Statement History</a></td></tr>