simple php pagination or css pagination with php/mysql - php

I am trying to built a simple php pagination ( a sort of ).
or to be more specific css pagination with php/mysql.
Accessing and storing the values from db
while($row = $result->fetch_assoc()) {
$id[]=$row["id"];
$name[]=$row["name"];
$url[]=$row["url"];
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["url"]. "<br>";
}
Displaying them
<ul class="pagination">
<li>«</li>
<?php
$i=1;
for ($x = 0; $x < count($id); $x++) { ?>
<li>
<a href=<?php echo "$url[$x]"; ?> target="iframe1"
title="<?php echo "$name[$x]"; ?>"><?php echo "$i";?></a>
</li>
<?php $i++;} ?>
<li>»</li>
</ul>
Once any number shown above is clicked required url is displayed inside iframe1
<div align="center">
<iframe name="iframe1" src="http://www.w3schools.com"
frameborder='0' height='1000' width='1000' align="center"></iframe>
</div>
when I click any number it display the url inside the iframe "iframe1" .
Question:
How do i display first and NEXT {NOT LAST} record in
<li>«</li> [First]
<li>»</li> [Next]
I am looking for a very small code to do the same.

The first link is pretty easy:
<a href=<?php echo "$url[0]"; ?> target="iframe1"
title="<?php echo $name[0]"; ?>"><<</a>
For next link It would kind of depend on how your urls are set out. If the $url values are just a name and your url is domain.com/blog?page=page1 where page1 is the value from $url then we get use $_GET['page'] to grab the current page. Then using:
$next = array_search($_GET['page'], $url);
will give us the number in the order of the current page so the next page will simply be $url[$next + 1]
EDIT:
OK if its a url that changes in domain part then the $_GET wont work. You could grab the current url using $_SERVER[REQUEST_URI] and then use the same technique as above to find its position in the array of urls.

Related

Advice on cleaner way to write this While statement

So the following code works, it is doing everything i want it to do. However, as i step back it seems like an overly convoluted approach to what is arguably one of the most common tasks in php.
I know enough about php to figure out what most things are doing when i see them, and to create some rather ugly code like you will see below; however, the finer points evade me.
I was hoping that if someone had some free time, he/she could look this over and show me a more concise way to approach this.
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<div id="item_gallery_s'.$i .'"'. 'class="fluid profileImgWrap goldDiagGrad">' .
'<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">' .
'<a href="http:#"
target="_blank"
title="some title">' . $row['place'] .
'</a></span></div><!-- DCD Diva Name -->' .
'<a rel="events[events]"
href="#">' .
'<div class="profile_banner">Custom Banner</div><!-- Banner -->' .
'<img src='.'"img/upload/'.$row['icon'].
'"' .
'alt="image description |'.$row['name'].
'"/>' .
'<!-- Photo --></a></div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}?>
The loop itself is fine but you'll find varying opinions on the HTML-in-strings. For the past seven years I've encouraged my team to either use HTML with php tags or we rely on a full templating system:
<?php while ($row = mysql_fetch_assoc($result)): ?>
<div><?= $row['something'] ?></div>
<?php endwhile ?>
Though we have short tags enabled for even cleaner code. The benefit of this is that it's cleaner - less quotes, escaping problems, and IDEs will be able to syntax highlight the html. Most treat the html as string when it's inside quotes.
That's as "concise" as it gets.
You could not use an echo inside the while. And use php short tags.
while ($row = mysql_fetch_assoc($result)) {
?>
<?=$row['place'];?>
<?php
}
?>
Another way to "clean up", would be to use a template engine, but once again that would be just for the HTML part.
{place}
Good coding!
You can clean this up a bit by interspersing actual HTML, rather than simply echoing it:
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
?>
<div id="item_gallery_s<?php echo $i; ?>" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">
<?php echo $row['name']; ?>
<br />
<span class="profile_date"><?php echo $row['place']; ?></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#"><div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/<?php echo $row['icon']; ?>" alt="image description |<?php echo $row['name']; ?>"/><!-- Photo --></a>
</div><!-- END #item_gallery_s<?php echo $i; ?> -->
<?php
$i++;
}?>
Another option, depending on how much work like this you have to do, would be a full-blown template engine such as Smarty.
Here's how I would probably format this code (as a matter of personal style):
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo
'<div id="item_gallery_s'.$i.'" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">
<a href="http:#" target="_blank" title="some title">' . $row['place'] .
'</a></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#">
<div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/' . $row['icon']. '"
alt="image description |' . $row['name']. '"/>
<!-- Photo -->
</a>
</div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}
?>
Try also to use consistent indentation to make it easy to tell what matches up with what. By the way, a <div> (block element) inside an <a> (inline element) is bad form. Did you mean to use a <span>? Learn to use the W3C validator to pick up this stuff.

Refreshing div with ajax loses link to javascript file

I have a div that includes shoutbox posts. I'm using jQuery and ajax to change the pages within the div. However, when the page changes, it loses the link to the javascript file so that the next time I try to change the page it actually continues with the link action instead of doing the ajax in the background. Then after that it's back to normal and it alternates back and forth between being linked to the file and not.
Also before, it was rendering the whole page so that my layout was being displayed on the refresh instead of just the shoutbox posts. I'm guessing that finally getting it to refresh without re displaying the whole layout again is what's causing it to lose the connection to the javascript file.
This is the code for the posts. The shoutbox_arrows contains the links to change the page. refresh_me is what I'm loading into my div to refresh the content.
<div id="shoutbox_arrows">
<?php $current_page=s tr_replace( '?', '#', getURI(fullURL())); ?>
<ul class="no_dots">
<li id="first_page"><<
</li>
<li id="previous_page"><
</li>
<li><strong>Pg#<?php if ($page > $last_page) {echo $last_page;} else {echo $_SESSION['shoutbox_page'];} ?></strong>
</li>
<li id="next_page">>
</li>
<li id="last_page">>>
</li>
</ul>
</div>
<div id="shoutbox" class="custom_scrollbar">
<div id="refresh_me">
<?php if (sizeof($shouts)==0 ) { ?>
<p>There are no posts.</p>
<?php } foreach ($shouts as $shout) { foreach ($shout as $k=>$v) { $shout[$k] = utf8_encode($v); if ($k == 'guest') { $shout[$k] = ucwords($v); } } ?>
<div class="post_info">
<div class="left">
<?php if ($shout[ 'user_id']==n ull) {echo $shout[ 'guest'];} else { ?><?php echo ucwords(userinfo($shout['user_id'])->username); ?>
<?php } ?>
</div>
<div class="right">
<?php time_format($shout[ 'created_at']); ?>
</div>
</div>
<p class="post_comment" id="shoutbox_comment_<?php echo $shout['id']; ?>">
<?php echo $shout[ 'comment']; ?>
</p>
<?php if (!$shout[ 'last_edited_by']==n ull) { ?>
<p class="last_edited">Edited by
<?php echo ucwords(userinfo($shout[ 'last_edited_by'])->username); ?>
<?php time_prefix($shout[ 'updated_at']); ?>
<?php time_format($shout[ 'updated_at']); ?>.</p>
<?php } ?>
<?php if (current_user()) { if (current_user()->user_id == $shout['user_id'] or current_user()->is_mod) { ?>
<p class="post_edit"> <span class="edit" id="<?php echo $page; ?>">
<a id="<?php echo $shout['id']; ?>" href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
edit
</a>
</span> | <span class="delete" id="<?php echo $page; ?>">
<a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
delete
</a>
</span>
<span class="hide" id="<?php echo $page; ?>">
<?php if (current_user()->is_mod) { ?> | <a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
hide
</a><?php } ?>
</span>
</p>
<?php }} ?>
<?php } ?>
</div>
</div>
This is the page that my ajax request is going to.
<?php
if (isset($data['page'])) {
$_SESSION['shoutbox_page'] = intval($data['page']);
}
$redirect = ltrim(str_replace('#', '?', $data['redirect']), '/');
redirect_to($redirect);
Div that contains the content to be refreshed.
<div id="shoutbox_container">
<?php relativeInclude( 'views/shoutbox/shoutbox'); ?>
</div>
jQuery
$('#shoutbox_arrows ul li a').click(function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
So I guess to clarify the issue:
The shoutbox_container displays posts for the shoutbox. The page is controller by a session that gets passed as a variable to get the correct chunk of posts to show. Clicking on the links in shoutbox_arrows sends an ajax request to a page which changes the session variable. The div that contains the post itself (refresh_me) as well as the arrows (for the links) get refreshed. After changing the page once, the shoutbox is no longer connected to the javascript file so when you click to change the page again, instead of an ajax request, the page itself actually changes to the link.
Any ideas how I can fix this? I've spent a lot of time on this and it's getting rather frustrating. I feel like I could just settle for it as it is now but it's bugging me too much that it's not working exactly how I intend (although generally it works in terms of changing the pages).
Also just a note, I used jsfiddle to tidy up the code but it looks like it did some funky stuff (looking just at $current_page=s tr_replace). lol. So there aren't any syntax errors if that's what you're thinking. ><
Also I was going to set up a fiddle but I don't really know how to handle links in it so it would have been useless.
The issue is that you bind the click handler to the a tags on document ready (the jQuery code you provided). So when you replace the content of #shoutbox_arrows you remove the click handler you previously attached since those original handlers are removed from the DOM along with the original elements.
You need to use the jQuery .on() method and event bubbling. This will attach the handler on a parent element that will not be removed in your content replace and can continue to "watch" for the event to bubble up from it children elements.
Try replacing your jQuery code with this:
$('#shoutbox_arrows').on('click', 'ul li a', function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
For performance, you should add a class to the a, and targeting it directly with $('a.aClass')
Good ways to improve jQuery selector performance?

Random banner display using php and mysql

I'm creating my website located here
I'm trying to add a banner that changes every time a page refreshes. I have set up 2 examples in my database called "link 1" and "link 2". I will want to add more as and when I get them.
What I want to happen is this:
I want to display one of the 2 images on my site and when the user refreshes the page, it will select one of the 2 images and this should continue every time the page refreshes.
I'm testing this out in a page called banner.php before I move it to my footer.php and make it live.
I currently have this code In my banner.php page:
<?PHP
include_once('include/connection.php');
// Edit this number to however many links you want displaying
$num_displayed = 1 ;
// Select random rows from the database
global $pdo;
$query = $pdo->prepare ("SELECT * FROM banners ORDER BY RAND() LIMIT $num_displayed");
$query->execute();
// For all the rows that you selected
while ($row = execute($result))
{
// Display them to the screen...
echo "<a href=\"" . $row["link"] . "\">
<img src=\"" . $row["image"] . "\" border=0 alt=\"" . $row["text"] . "\">
</a>" ;
}
?>
<br /><br /><br />
But I am getting this error code:
Fatal error: Call to undefined function execute() in banner.php on line 13
My connection page is used by other pages so I know it works.
Please can some one help me on what I am doing wrong.
Need any more info then please ask and I will add it to this post.
Thank you.
Kev
replace this
while ($row = execute($result))
with this:
while ($row = $query->fetch())
EDIT
This make it better to read.
while ($row = $query->fetch()) :
// Display them to the screen...
?>
<a href="<?php echo $row['link']; ?>">
<img src="<?php echo $row['image']; ?>" border="0" alt="<?php echo $row['text'];?>">
</a>
<?php endwhile; ?>
<br/>
<br/>
<br/>

adding multiple do statements on a page using php and mysql

Ok so I didn't see anything like this in the previous postings so if if has been covered before sorry for the repost.
I am trying to put a second do..while statement in the same page but when I do this it seems to drag down the page. it loads fine if I have only one statement in there but the minute I put in a second one it takes forever to load the page. I have a need of adding a total of 9 do..while statements which will most likely kill the page at this point. I'm not sure why it would be doing this any ideas?
The code I'm using is as follows
<p><?php
do {
$row_myContacts = mysql_fetch_assoc($myContacts);
if ($row_myContacts['staffID'] != "81"){
}
else {
echo $row_myContacts['firstName'] . " " . $row_myContacts['lastName'];?></p>
<p class="staff_title_national"><?php echo $row_nmyContacts['titleName'];?></p>
<br />
<li><?php echo $row_myContacts['address1']
. " " . $row_myContacts['address2'] ;?></li>
<li><?php echo $row_myContacts['cityName']
. ", " . $row_myContacts['state_abreviation'] . " "
. $row_myContacts['zipCode'];?></li>
<br />
<li>Office: <?php echo format_phone($new_office_phone); ?></li>
<li>Fax: <?php echo format_phone($new_fax_phone); ?></li>
<br />
<br />
<li>E-Mail:
<?php echo $row_myContacts['email'];?></li>
<br />
<?php }
} while ($row_myContacts['staffID'] != '81')?>
I have tried testing it so that the staffID is == to the number i need, but it doesn't output anything. I think it should be that way but for some reason it doesn't work. and yes I moved the stuff in that variation so that the else was empty and the if had the information in it.
The page holds 4 sections of contacts under section 1 there is one section with 2 names (same address info) section 2 has 3 names different info, sections 3 and 4 have 2 each with different info. I even created 2 new tables in my database that reference the 4 sections if that helps. I do know my sql statement is correct it pulls all 9 contacts with their corresponding information.
/edit below/
so I also tried the code this way. and I do get it to load the first one but when I add a section for loop it shows nothing. I think it is because I am telling the loop to access the database at the same point that it left off so it isn't starting over on the loop.
<?php
for ($x=$totalRows_myContacts; $x>=1; $x--){
if ($row_myContacts['staffID'] == '81') {
echo $row_myContacts['firstName'] . " " . $row_myContacts['lastName'];?></p>
<p class="staff_title"><?php echo $row_myContacts['titleName'];?></p>
<br />
<li><?php echo $row_myContacts['address1'] . " " . $row_myContacts['address2'] ;?></li>
<li><?php echo $row_myContacts['cityName'] . ", " . $row_myContacts['state_abreviation'] . " " . $row_myContacts['zipCode'];?></li>
<br />
<li>Office: <?php echo format_phone($new_office_phone); ?></li>
<li>Fax: <?php echo format_phone($new_fax_phone); ?></li>
<br />
<br />
<li class="emailTealGrey">E-Mail: <?php echo $row_myContacts['email'];?></li>
<br />
<?php }$row_myContacts = mysql_fetch_assoc($Contacts);
}?>
so not sure how to tell the database to access itself again and start the query from the top I guess is what I need to do. any ideas how to tell it to do that?
What happens if there is no row for staffID=81
change code to something like this,
.....
do {
$row_myContacts = mysql_fetch_assoc($myContacts);
if ($row_myContacts == false){
break;
}
.....

php order by 'most recent' 'most liked' 'least like'

I have a post system in place
<?php
/**
Display the results from the database
**/
$q = ("SELECT * FROM threads ORDER BY posted");
$r = mysql_query($q);
if(mysql_num_rows($r)>0): //table is non-empty
while($row = mysql_fetch_assoc($r)):
$net_vote = $row['votes_up'] - $row['votes_down']; //this is the net result of voting up and voting down
?>
<div class='entry'>
<span class='link'>
<?php echo $row['author']; ?>
<?php $row['posted'] = date("jS M Y h:i",$row['posted']); echo $row['posted']; ?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo $row['message']; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<br/>
<div class='message'><?php echo $row['message']; ?><br/></div>
<?php echo "<a href='msg.php?id=$row[id]'/> Comments/Add comments $row[replies]</a>" ?>
<?php echo "Likes: " . $row['votes_up'] . "&nbsp "; echo "Dislikes: " . $row['votes_down'] . "&nbsp"; ?>
</span>
<span class='votes_count' id='votes_count<?php echo $row['id']; ?>'></span>
<span class='vote_buttons' id='vote_buttons<?php echo $row['id']; ?>'>
<a href='javascript:;' class='vote_up' id='<?php echo $row['id']; ?>'></a>
<a href='javascript:;' class='vote_down' id='<?php echo $row['id']; ?>'></a>
<br/>
</span>
</div>
<br/>
<?php
endwhile;
endif;
?>
I want to add text that says 'order by : Most recent | Most liked | least liked '
As you can see i think ive got it already posting most recent by defualt which is what i want.
But what i want also is when you click 'Most liked' & 'least liked' it sorts by 'Vote_up' ( likes) & 'vote_down' (dislikes) all on the same page and shows posts with most likes on them (most liked) and most dislike (least liked)
EDIT***
sorry my question is how can i add 2 functions that when on click sorts by 'most liked' and 'least liked'
in html:
<a href='script.php?order=recent'>Recent</a>
<a href='script.php?order=liked'>Liked</a>
...
in php:
if ($_GET['order'] == 'recent') $order = "posted";
elseif ($_GET['order'] == 'liked') $order = "smth";
...
$q = "SELECT * FROM threads ORDER BY ".$order."";
but actually it's better to use some js framework (i prefer extjs for that) to sort the output on client side
AFAIK you have few choices how to do this:
Have the links pass a $_GET value via URL (causes a page refresh!!), then test for this in the PHP and run the necessary SQL to get the new record order.
Use AJAX to perform the same request asynchronously, with a PHP script to handle the SQL function and return the desired results.
Use a jQuery plugin such as tablesorter to (probably) basically provide the same functionality as that in 2, or via it's own filtering system -- I'm not sure i've not used it!!
My preference would be 1. (i.e a pure PHP + MySQL solution) as this offers the best universal functionality. You could always add javascript / ajax later to make things more swish for more modern browsers and users!

Categories