changing colors when link is clicked - php

If I have a menu set up in the header which I use for most of my pages as "include/header.php" how do I setup so when I click on a link, it goes to that page, and that link changes colors (and shows as active)? Would jquery be good? or PHP?
Thanks!

You could use PHP to add a class to the current button by comparing it's URL, and the current page URL from $_GET. Without knowing what your URL structure is like, I can't say much more than that.
For example, using an array with button text and URLs:
$links = array('Home' => 'home', 'About' => 'about');
foreach($links as $text => $page)
{
if($_GET['page'] == $page)
{
echo '' . $text . '';
}
else
{
echo '<a href="/index.php?page=' . $page . '>' . $text . '</a>';
}
}
This code will add a class of current to the button who's page matches the value in $_GET. This might not exactly fit your needs due to you probably having a different URL structure, among other things, but it gives a basic explanation and example of how to do this.

Use php, you could write a function before your include like so,
function activeLink ($page) {
if ($page = 'home') echo ' class="active"';
elseif ($page = 'about') echo ' class="active"';
elseif ($page = 'posts') echo ' class="active"';
}
And in your header file,
echo '<a href="#"' . activeLink($page) . '>Home</a>
<a href="#"' . activeLink($page) . '>About</a>
<a href="#"' . activeLink($page) . '>Posts</a>';
And on your actual page;
$page = 'home';
include('header');
This will do the trick.

Related

codeigniter how to restrict number of url segments in a page

I am having a codeigniter function that does searching which is working fine but the issues arises when I am making a new search on a single page whereby on clicking search button the same url of the single page duplicates on the url bar thus taking me to a wrong link. see how it behaves in the below snippets;
http://localhost/newsapp/bulletins/view/31
http://localhost/newsapp/bulletins/view/view/31
http://localhost/newsapp/bulletins/view/view/view/31
http://localhost/newsapp/bulletins/view/view/view/view/31
here are the functionss;
public function livesearch() {
$keyword = $this->input->post('keyword');
$query = $this->news_model->get_live_items($keyword);
foreach ($query as $row):
echo "<li><a href='view/$row->id'>" . $row->title . "</a></li>";
endforeach;
}
This one displays the search results in a another page:
public function search_keyword()
{
$keyword = $this->input->post('keyword');
$data['results'] =$this->news_model->get_live_items($keyword);
$data["top_news"] = $this->news_model->topnews();
$data["latest_news"] = $this->news_model->latestnews();
$this->load->view('result_view',$data);
}
finally this where all the magics are happening;
function view($id)
{
$data['news'] = $this->news_model->get_one_news($id);
$data["top_news"] = $this->news_model->topnews();
$data["latest_news"] = $this->news_model->latestnews();
$data['content'] = 'single'; // template part
$this->load->view('includes/template',$data);
}
Your livesearch method should be
public function livesearch() {
$keyword = $this->input->post('keyword');
$query = $this->news_model->get_live_items($keyword);
foreach ($query as $row):
echo "<li><a href='" . base_url('bulletins/view/' . $row->id) . "'>" . $row->title . "</a></li>";
endforeach;
}
Try giving a full link like this
echo "<li><a href='".base_url()."view/$row->id'>" . $row->title . "</a></li>";
You are just including the view/$row->id so it is adding the url rather than generating the required url.

How do I create a prev/next function for a one page display site?

I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}

Displaying all list items while using a foreach loop in php

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

Using PHP to show "Next" an "Previous" in pagination

I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination

How to properly build a navigation menu that highlights the current page

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>

Categories