I want to modify this code which works pretty good but (or I don't know because I'm new with php) I can't limit the number of li's displayed for the main elements in the menu. The actual code will echo all elements it finds, I want to limit the times
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
this line is echoed.. let's say to echo just the first 15 elements + a "MORE" button under which to display the rest of the elements as sub-menus.. (this is a 2 level horizontal menu). Can someone please help me? I really tried a lot but I'm not an expert in PHP..
Thanks!
<?php
require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );
class SimpleMenu extends TemplMenu
{
function getCode()
{
$this->iElementsCntInLine = 100;
$this->getMenuInfo();
$this->genTopItems();
return $this->sCode;
}
function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
{
$sActiveStyle = ($bActive) ? ' id="tm_active"' : '';
if (!$bActive) {
$sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
$sTarget = $sTarget ? ( ' target="_parent"' ) : '';
}
$sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;
$sSubMenu = $this->getAllSubMenus($iItemID);
$sImgTabStyle = $sPictureRep = '';
if ($isBold && $sPicture != '') {
$sPicturePath = getTemplateIcon($sPicture);
$sPictureRep = "<img src='{$sPicturePath}' style='vertical-align:middle;width:16px;height:16px;' />";
$sText = ' ';
$sImgTabStyle = 'style="width:38px;"';
}
$sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} </a>";
$this->sCode .= "
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
<div id='submenu'>
<ul>
<li>{$sMainSubs}</li>
</ul>
</div>
</li>
";
}
}
$objMenu = new SimpleMenu();
echo "<ul id='ddmenu'>";
echo $objMenu->getCode();
echo "</ul>";
?>
It's difficult to tell exactly where you want to do this in your code, but I figure you're looking for something like:
<?php
for ($i = 0; i < 15; i ++){
echo "<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>"
}
echo "<li><a href='more' target='_parent'>More...</a>"
?>
Related
First of all, I will try and keep this as simple as possible.
This is part of a larger script that generates a breadcrumb link list depending on which category the user is currently in on the page.
Something like:
Hats > Mens > Green
Each of the categories also have their corresponding links so the user can click back on it.
The problem I'm having is that for some reason, I'm getting an additional link inserted that is the current category, right before the top category.
For example, the output, should be:
<b>Category:</b>
Hats >
Mens >
Green
But I am getting this:
<b>Category:</b>
Hats >
<a href="categories.php?parent_id=175828&name=Green&keywords_search=" title="">
Mens >
Green
</a>
Note that the difference is that the current category link (but without the name) gets inserted almost at the very top again, in addition to an additional link closing tag at the very end as well.
What could be the problem? I've spent nearly 6 hours on this and can't figure it out, so I'd really appreciate it if someone could tell me what is wrong. Maybe I spent too much looking at this and am "stuck inside the box" :)
function category_navigator ($parent_id, $show_links = true, $show_category = true, $page_link = null, $additional_vars = null, $none_msg = null, $reverse_categories = false)
{
global $reverse_category_lang, $category_lang, $db;
(string) $display_output = NULL;
(int) $counter = 0;
$none_msg = ($none_msg) ? $none_msg : GMSG_ALL_CATEGORIES;
$page_link = ($page_link) ? $page_link : $_SERVER['PHP_SELF'];
if($parent_id > 0)
{
$root_id = $parent_id;
while ($root_id > 0)
{
$row_category = $db->get_sql_row("SELECT category_id, name, parent_id, hover_title FROM
" . DB_PREFIX . (($reverse_categories) ? 'reverse_categories' : 'categories') . " WHERE
category_id=" . $root_id . " LIMIT 0,1");
if($counter == 0)
{
$display_output = ($reverse_categories) ? $reverse_category_lang[$row_category['category_id']] : $category_lang[$row_category['category_id']];
$display_output = (!empty($display_output)) ? $display_output : $row_category['name'];
$ace = $row_category['category_id'];
$acename = $row_category['name'];
}
else if($parent_id != $root_id)
{
$hover = $db->get_sql_field("SELECT hover_title FROM " . DB_PREFIX . "categories WHERE category_id='".$ace."'","hover_title");
$category_name = ($reverse_categories) ? $reverse_category_lang[$row_category['category_id']] : $category_lang[$row_category['category_id']];
$category_name = (!empty($category_name)) ? $category_name : $row_category['name'];
$display_output = (($show_links) ? '<a href="' . $page_link . '?parent_id=' . $row_category['category_id']
. '&name=' . $category_name . ((!empty($additional_vars)) ? ('&' . $additional_vars) : '')
. '" title="'.$row_category['hover_title'].'">' : '') . $category_name . (($show_links) ? '</a>' : '</a>')
. ' > <a href="'. $page_link . '?parent_id=' . $ace . '&name=' . $acename . ((!empty($additional_vars)) ? ('&' . $additional_vars) : '')
. '" title="'.$hover.'">' . $display_output . '</a>';
}
}
$counter++;
$root_id = $row_category['parent_id'];
}
$display_output = (($show_links && $show_category) ? '<b>Category:</b>' : '') . $display_output;
}
$display_output = (empty($display_output)) ? $none_msg : $display_output;
return $display_output;
}
I have script which I use to create top navigation on my site.
My problem, I do not know how to add class last to the class that is already used to the last element of an array to make it look class="tab selected last" when selected or class="tab last" when not selected. Class last will get rid of the divider line on the right of the nave menu element.
here is my script
while ($info = $res -> fetch()){
$link_lbl = $info['link_lbl'];
$link_dir = $info['link_dir'];
$link_url = $info['link_url'];
$link = ($link_dir == NULL) ? SITE_DOMAIN.DST.$link_url : SITE_DOMAIN.DST.$link_dir.DS.$link_url;
$link_title = $info['link_title'];
$selected = ($info['ID'] == $number) ? 'tab selected' :('tab');
$rd_div = ($info['link_show'] == 1) ? '<div><a class="'.$selected.'" href="'.$link.'" title="'.$link_title.'">'.$link_lbl.'</a></div>' : ('');
print<<<END
$rd_div
END;
}
Please help.
I have tried to use end($rd_div) to find the last element, but do not know how to change it.
Thanks in advance
$rowNum = 0;
while ($info = $res -> fetch()){
$rowNum++;
// ...
$last = ($rowNum == $res->rowCount()) ? ' last' : '';
$rd_div = ($info['link_show'] == 1) ? '<div><a class="'. $selected . $last . '" href="'.$link.'" title="'.$link_title.'">'.$link_lbl.'</a></div>' : ('');
I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});
I've been trying to figure out how to make the last item in my breadcrumb have H1 tags in it. Here is a sample code without the H1.
// Each tree item has a URL and name. Some may have extra_before and extra_after.
foreach ($context['lateral_navigation'] as $link_num => $tree)
{
echo '
<li', ($link_num == count($context['lateral_navigation']) - 1) ? ' class="last"' : '', '>';
// Show something before the link?
if (isset($tree['extra_before']))
echo $tree['extra_before'];
// Show the link, including a URL if it should have one.
echo $settings['lateral_navigation_link'] && isset($tree['url']) ? '
<a href="' . $tree['url'] . '">' . $tree['name'] . '
</a>' : '' . $tree['name'] . '';
// Show something after the link...?
if (isset($tree['extra_after']))
echo $tree['extra_after'];
echo '
</li>';
I'm not a PHPer, and I've tried experimenting with it code on this line:
<li', ($link_num == count($context['lateral_navigation']) - 1) ? ' class="last"' : '', '>';
Because it shows the "last" only on the last item of the breadcrumb.
I tired this below, but obviously it didn't work:
// Each tree item has a URL and name. Some may have extra_before and extra_after.
foreach ($context['lateral_navigation'] as $link_num => $tree)
{
echo '
<li', ($link_num == count($context['lateral_navigation']) - 1) ? ' class="last"><h1>' : '', '>';
// Show something before the link?
if (isset($tree['extra_before']))
echo $tree['extra_before'];
// Show the link, including a URL if it should have one.
echo $settings['lateral_navigation_link'] && isset($tree['url']) ? '
<a href="' . $tree['url'] . '">' . $tree['name'] . '
<div id="arrow">
<div class="inside"></div>
<div class="border"></div>
</div>
</a>' : '' . $tree['name'] . '';
// Show something after the link...?
if (isset($tree['extra_after']))
echo $tree['extra_after'];
// Don't show a separator for the last one.
if ($link_num != count($context['lateral_navigation']) - 1)
echo '';
echo '
</h1', ($link_num == count($context['lateral_navigation']) - 1) , '></li>';
}
Any help with this?
Try this:
$count = count($context['lateral_navigation']); // get count
// Each tree item has a URL and name. Some may have extra_before and extra_after.
foreach ($context['lateral_navigation'] as $link_num => $tree)
{
$count--; // decrement by 1
echo ($count == 0) // if zero (last)
? '<li class="last"><h1>'
: '<li>';
// Show something before the link?
if (isset($tree['extra_before']))
echo $tree['extra_before'];
// Show the link, including a URL if it should have one.
echo $settings['lateral_navigation_link'] && isset($tree['url']) ? '
<a href="' . $tree['url'] . '">' . $tree['name'] . '
<div id="arrow">
<div class="inside"></div>
<div class="border"></div>
</div>
</a>' : '' . $tree['name'] . '';
// Show something after the link...?
if (isset($tree['extra_after']))
echo $tree['extra_after'];
// Don't show a separator for the last one.
if ($link_num != count($context['lateral_navigation']) - 1)
echo '';
echo ($count == 0) // if zero (last)
? '</h1></li>'
: '</li>';
}
I'm running a while loop which is taking rows from mySQL and echo'ing them out. Pretty standard. However, there needs to be different HTML markup for the first item, next two items, then it continues as normal into the while loop.
Currently, my while loop looking something like this:
while( ( $row = mysql_fetch_object( $result ) ) !== false )
{
// Places ad based of predefined variable frequency
if ($ad == $adFrequency){
echo '<div class="one-advertisement-article clearfix">';
echo '<div class="grid_9 suffix_2"><img src="http://placehold.it/263x75/000000/ffffff"></div>';
echo '<div class="grid_1"><a class="navigate-right-icon ss-icon" href="#">navigateright</a></div>';
echo '</div>';
$ad = 0;
}
echo '<div class="one-news-article clearfix">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="grid_4"><img src="'.$image_url.'"></div>';
}
else {
echo '<div class="grid_4"><div class="news-placeholder"><span class="ss-icon">ellipsischat</span></div></div>';
}
echo '<div class="grid_7">';
echo '<h2>'.$row->title.'</h2>';
$published_date = date('D, d M Y', strtotime($row->datein));
echo '<p class="published-date">'.$published_date.'</p>';
echo '</div>';
echo '<div class="grid_1">';
echo '<div class="news-item-vertical-sep"> </div>';
echo '<p></p>';
echo '</div>';
echo '</div>';
$ad++;
}
This works fine, but I need to take the first three news items and use this:
echo ' <div class="one-news-featured-article clearfix">';
echo ' <div class="grid_12">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="large-featured-image-container"><img src="'.$image_url.'">/div>';
}
echo ' <div>';
echo ' <h2>'.$row->title.'</h2>';
echo ' </div>';
echo ' </div>';
echo ' </div>';
echo ' <div class="grid_6">';
Any help? Essentially, it needs to apply the second code to the first three items in the query, then follow through with the code included in the current while loop - like an offset I guess.
Thanks,
R
This is quite simple. I hope I understood your question correctly:
$i = 0;
while ( ( $row = mysql_fetch_object( $result ) ) !== false ) {
if ($i < 3) {
// First code
} else {
// Second code
}
$i += 1;
}
Firstly, you should avoid using any mysql_ functions as they are all deprecated and will be removed from future versions of PHP. I'd recommend using PDO instead. See this tutorial to get started.
Then, it'll simply be a case of doing something like this:
foreach($db->query($query) as $index => $row) {
if ($index < 3) {
// first 3 items
} else {
// other items
}
}
You can do it easaly with an simple counter and an if statement:
$count = 0;
while(fetching) {
if($count < 3) {
// items 1, 2 and 3
} else {
// do normal
}
$count++;
}