I am building a navigation system on a webpage using PHP, that basically queries data from MySQL database and display as ul, li menu on main menu. But I couldn't figure out how do I make navigation menu selected when user goes to that page. I have one idea but that doesn't make home menu selected by default when user enters that page.
I have also a CSS class written to give that class to the anchor tag if it is that page.
here is my PHP code:
//Query Functions
function queryMenu() {
$query = "SELECT * FROM menu_en";
return $query;
}
// Render Functions
function renderNav() {
$menus = queryMenu();
$queryMenu = mysql_query($menus);
while( $navigation = mysql_fetch_array($queryMenu) ){
if( $navigation['id'] == $_GET['pageId'] ){
echo '<li>
<a href="index.php?pageId="'.$navigation['id'].' class="selected" >'.$navigation['menu_title'].
'</a></li>';
}else{
echo '<li><a href="index.php?pageId="'.$navigation['id'].'>'.$navigation['menu_title'].'</a></li>';
}
}
}
Suggest me a better way to do this, as I want to enhance my skill in PHP. And also please let me know if there is any wrong approach in above code.
If the home page is when $_GET['pageId'] is not set you could check using isset()
if(isset($_GET['pageId'])) {
$page = $_GET['pageId']
} else {
$page = $homePageId; // the ID of the home page.
}
Then you would replace this line:
if( $navigation['id'] == $_GET['pageId'] ){
with this line:
if( $navigation['id'] == $page ){
I think this would work, if i understand you correctly.
Related
EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.
There are two ways of writing php snippets to place html on the home page and then html on all other pages... This is for Joomla 3.++
<?php
$menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault()) {
echo 'HTML for HOME PAGE HERE';
} else {
echo 'HTML for ALL OTHER PAGES HERE';
} ?>
This code allows for just focusing on the home page only:
<?php
$menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault()) {
echo 'HTML FOR HOME PAGE HERE';
}
?>
What I would like to do, specifically like the second code snippet, is focus on specific pages on the site....
The reason being is A. I don't want to create a template for every other page type I am creating... And B. I don't want to have to place template elements of styling in my html module positions. I feel the custom HTML or blog / article posts should simply be for content insertion.
So is there a way to instead of calling on the $menu->getDefault()) <<<< make that getPage???
Use JInput to get the page information from the request.
Found the answer. You can do a direct page edit and ifelse edits for multiple pages.
<?php
//This is the code for the page with menu ID 102
$menuID = JSite::getMenu()->getActive()->id ;
if ($menuID == '102')
{
echo '<strong>long</strong>';
}
?>
Here is the code for multiple pages.
<?php
//This is the code for the page with menu ID 6
$menuID = JSite::getMenu()->getActive()->id ;
if ($menuID == '6')
{
echo '';
}
elseif ($menuID == '2') //This is the HTML for page with menu ID 2
{
echo '';
}
elseif ($menuID == '4') //THis is the html for page with menu id 4
{
echo '';
}
else //This is the HTML code for the rest of the pages
{
echo '';
}
?>
Found the answer here.
Joomla if else for menu by ID or url
I have a menu which get its items from database.
I want to get the menu id of clicked menu in following for each:
public function gen_menu($menuItems, $pId = 0)
{
$menu = '';
$ulStart = 0;
$base_url = base_url();
$uri = $this->uri->segment(1);
foreach($menuItems as $row)
{
if($row->parent_id==$pId)
{
if($ulStart==0) { $menu .= "<UL>"; $ulStart++; }
$url = $row->item_url;
stripos($url,$base_url)===0 || $url==""?$base_url = base_url():$base_url="";
{
if($row->external==1){
$menu .= '<LI>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
else{
$class = ($uri==$row->custom_url)?"class='selected'":"";
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
}
}
}
if($ulStart!=0) { $menu .= "</UL>"; }
return $menu;
}`
When I am using onclick in it returns the last id of table always.
Try this:
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
You had $row->item_id inside the quoted string, so it wasn't expanded. You should have gotten a javascript error from that.
UPDATE:
The problem you're having is that you're confusing server-side and client-side actions. The code in this PHP script all runs on the server when it's creating the page to send to the user. If you're setting a session variable in the loop, the variable will contain the value from the last iteration. Putting PHP code inside onclick doesn't run it when the user clicks, it runs it when the server is composing the onclick attribute to put in the HTML that gets sent to the browser.
If you want to do something on the server when the user clicks, you need to put a Javascript function in the onclick attribute, and that function should use AJAX to call another PHP script.
I have a situation whereby i want two of my pages to look different form the rest but they are not front pages. If they were it would be easy as the code below would do the trick.
$menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault()) {
echo 'This is the front page';
esle(do something else)
}
?>
In short i want a similar approach but this time, to get the menu by ID/URL. Any ideas?
I got the answer to this...all you need to check is the menu ID then put the code below.
<?php
//This is the code for the page with menu ID 6
$menuID = JSite::getMenu()->getActive()->id ;
if ($menuID == '6')
{
echo '';
}
elseif ($menuID == '2') //This is the HTML for page with menu ID 2
{
echo '';
}
elseif ($menuID == '4') //THis is the html for page with menu id 4
{
echo '';
}
else //This is the HTML code for the rest of the pages
{
echo '';
}
?>
Page ItemId can be obtained using $itemid = JRequest::getInt( 'Itemid' );
I have this script that displays all the users images which i will display below.
My question: Is there a way I can display the first 10 images in the MySQL database and have the script hide the rest of the users images until the user clicks the link View All and have the rest of the images slide down when the user clicks the link?
Here is my PHP & MySQL script?
$multiple = FALSE;
$row_count = 0;
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['url'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Split the images into two parts. And set the second part to be hidden. Then add a click handler to slideDown. Here is the code:
UPDATE: it's not necessary to put the first 10 images into a div, but won't hurt either.
PHP
<?php
//echo '<div id="images">'; // visible images
while($row = mysqli_fetch_array($dbc)) {
// other stuff
// ...
// after the 10th image (0-9)
// open the hidden div
if ($i == 9) {
//echo '</div>'; // end of visible images
echo '<div id="hidden">'; // hidden images
}
}
echo '</div>'; // end of hidden
echo 'view all'; // view all
?>
jQuery
$(document).ready(function(){
$("#hidden").hide();
$("#view_all").click(function(){
$("#hidden").slideDown();
});
});
See it in action
Note: be sure not to hide the div with CSS. You do it in jQuery, and by this you allow users with JS disabled to get the content.
I'm not sure how many, or how large these images are, but if you want to make this scalable, I'd suggest doing an ajax callback that retrieves and fills in the "hidden" images, if the user requests them.
Yes, in your loop echoing out the list items, add the style="display:hidden" class="hidden" attribute when the count is > 10. Then use the window's scroll event to detect when the browser is scrolled near to the bottom of the window and then use jQuery to show the first hidden list item.
EDIT: This actually will show the items as the user scrolls down and does not need a "Show all button".
JQuery:
$(".hidden").hide();
$(window).scroll(function(){
if ($(window).scrollTop()+$(window).height > $("li:hidden:first").offset().top - SOMEPADDING )) {
$("li:hidden:first").fadeIn(200);
}
}