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

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

Related

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

php echo iframe or image

Hey everyone I am having an issue with echoing an image or an iframe, the idea is there is an image link or an iframe in the same row in the database & i want to only echo what the string content is, if it echos the iframe there is a blank space of an image & underneath is the youtube video, if it echos the image the iframe does not show, they both currently echo the same row id labled url, I only want one to echo based on the string content instead of both echo's.
Here is the code I use to fetch the stuff, its only the echo area you want to pay attention to, I am not sure what kind of, if or else statement i could put in here.
< ?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 4;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM bookmarks WHERE 1 ORDER BY id DESC LIMIT $limit OFFSET
$offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
echo '<img src=' . $row['url'] . '></br>'; /*here */
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
} }
?>
This script is a get results php
The best solution would be to save the data in different columns in the database. But if you want to keep the current structure would be able to check if the string contains HTML, then it is an iframe. Otherwise it is a link to the image.
<?php
if($row['url'] == strip_tags($row['url'])) {
//No HTML in string = link
echo '<img src="' . $row['url'] . '" alt="" />';
} else {
//Contains HTML = iframe
echo $row['url'];
}
?>
This assumes that you in your database have saved the values as either http://www.exempel.com or <iframe src =" http: // www ... ">. If the iframe-value also consists only of a URL, you must use another solution.
If you know whether the url is an image or video when you save them in the database then you could add another field for the media type. You could then use this in an if statement in your code, for example:
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
if ($row['mediaType'] === 'image') {
echo '<img src=' . $row['url'] . '></br>'; /*here */
} if ($row['mediaType'] === 'video') {
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
}
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
}
}

PHP Performing a persistent DB check

I'm actually trying to create a ( more or less ) instant chat.
There's just one thing left to go, until it's finished. And that's a DB check for new entries every second by PHP itself.
A while loop works great for it, because i can exit it perfectly.
The Problem is, that the "every second" thing isn't working.
I tried a sleep(1), but that causes a 1 minute server freeze, until the script has been completed.
Hope someone can help me, i'm actually frustrated about this problem.
elseif($latestID != 'undefined' && $_POST['returnafter'] == '60')
{
$timeout = '60';
$i = '0';
while ($i != $timeout)
{
$chat_content = "";
$i++;
$getLastID = mysql_query("SELECT id, userid, content, time_posted FROM (SELECT * FROM chat_system ORDER BY id DESC LIMIT 150) chat_system WHERE id > '" . $latestID . "' $extraQuery ORDER BY id ASC");
while ($lastID = mysql_fetch_object($getLastID))
{
$rowID = $lastID->id;
$user_posted_id = $lastID->userid;
$chat_content = $lastID->content;
$chat_posted = $lastID->time_posted;
$getUserData = mysql_query("SELECT username, avatar, loggedIn FROM account_data WHERE account_id=('" . $user_posted_id . "')");
while ($userData = mysql_fetch_object($getUserData))
{
$username = $userData->username;
$useravatar = $userData->avatar;
$loginStatus = $userData->loggedIn;
}
if ($loginStatus == '1')
{
$onlineStatus = '<img src="./images/3DArt/newOnline.png" class="chat_onlineStatus">';
}
else
{
$onlineStatus = '<img src="./images/3DArt/newOffline.png" class="chat_onlineStatus">';
}
if (date('Y-m-d', $chat_posted) == date('Y-m-d'))
{
$time_posted = strftime('Heute, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) == date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime('Gestern, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) < date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime("%A, %d %B %Y %H:%M", $chat_posted);
}
if (isset($_POST['parseEmoticons']) && $_POST['parseEmoticons'] == 'true')
{
$chat_content = emoticons($chat_content);
}
$newChatRow.= '<div class="chatRow" id="' . $rowID . '">
<div class="chatRow_container">
<div><img src="' . $useravatar . '" class="chatAvatar">' . $onlineStatus . '<b>' . $username . '</b>
</div>
</div>' . $modActions . '
<div class="chat_mainMsg">
' . $chat_content . '
</div>
<div class="chatTime">' . $time_posted . '</div>
</div>';
}
$content = str_replace(array(
'\r\n',
'\r',
'\n'
) , "<br />", $newChatRow);
if(!empty($chat_content)) { echo $newChatRow; $i = $timeout; return false; }
if(empty($chat_content)) { sleep(1); return true; }
}
}
I think, this informations should be enough. If not, just ask.
EDIT: The request is initialized by Ajax and on success the request repeats.
That's why PHP have to check for 60 seconds.
you should let the clientside decide what messages it "like" to receive.
eg you call your messages.php class - per ajax on the client side and pass a timestamp when the last time was the script requested new messages
example:
ajax interval with 1 second loop call the messages.php?last=123456 and receive all messages that were created after or equal this timestamp. now you update in javascript the last timestamp and so on.
or you use a perfect framework (if possible) that is designed perfectly for your task to solve this.
http://socket.io/ (or js keyword websockets)

Showing specific information of current user logged in, in PHP

I'm using this 2 plugins
http://www.wpexplorer.com/wordpress-user-contact-fields/
and
WooCommerce
The 1st parameter, in this case the number "1" refers to the id of the user, how con I change it to be dynamic? So, depending on the user I get its own specific information
<h2>Personal</h2>
<?php
echo '<ul>';
echo '<li>Direccion: ' .get_user_meta(1,'address',true) . '</li>';
echo '<li>Compañia: ' .get_user_meta(1,'company',true) . '</li>';
echo '<li>Birth dAte: ' .get_user_meta(1,'birth',true) . '</li>';
echo '<li>Gender: ' .get_user_meta(1,'gender',true) . '</li>';
echo '<li>phone: ' .get_user_meta(1,'phone',true) . '</li>';
echo '</ul>';
?>
thanks
Don't try to make a function do something it wasn't intended to do. Write your own. Especially for something this simple.
function getUserStuff($id, $item){
$item = mysql_real_escape_string($item);
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT `".$item."` FROM `users` WHERE `id` = '".$id."'");
$z = mysql_fetch_assoc($q);
return (mysql_num_rows($q) > 0) ? $z[$item] : false;
}
This is just an example. I used a deprecated function for simplicity but you should use a different API.

PHP undefined offset

I am making a photo gallery and with every photo I can see how many comments there are on that photo. The code that I have is working like it should except that if there are 0 comments it will give the 'Undefined Offset error: 2'
'Undefined Offset error: 3'
'Undefined Offset error: 4'
'Undefined Offset error: 5'
etc.
This is the code to check how many comments there are:
(reacties = comments)
// check how many comments every photo has.
$reacties;
$query = "select foto from fotosreacties where boek = '" . $_GET['boek'] . "'";
if($result = mysql_query($query)){
while ($r = mysql_fetch_array($result)){
while ($foto = current($fotoArray)) {
if ($foto==$r["foto"]){
$key = key($fotoArray);
} // end if
next($fotoArray);
} // end while
if(!isset($reacties[$key])){
$reacties[$key] = 1;
} // end if
else {
$reacties[$key]++;
} // end else
reset($fotoArray);
} // end while
} // end if
And this is the code to show the picture and the number of comments:
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
If anyone knows what I have done wrong and/or knows how to solve this it would be great!
You can embed the counter in your query:
select foto, count(*) AS counter_comments from fotosreacties where boek = '" . $_GET['boek'] . "'. In the result, you can use $r['counter_comments'] and check whether its 0 or more.
About your code:
Stop using MySQL-functions in new applications since they will be deprecated soon. Use MySQLi or PDO instead!
Never trust user input like $_GET, you at least sanitize it by (for example) mysql_real_escape_string().

Categories