paging next and previous links don't work! - php

can anyone help me with this code?the next and previous links don't work
$limit=20;
mysql_connect("localhost","root","");
mysql_select_db("autoschool") or die("Unable to select database");
$query = "select * from student";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "empty";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
$count = 1 + $s ;
while ($row= mysql_fetch_array($result)) {
$title = $row["id"];
echo "$count.)$title"."
" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
echo "
";
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print " <<
Prev 10&nbsp ";
}
$pages=intval($numrows/$limit);
if ($numrows%$limit) {
$pages++;
}
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
$news=$s+$limit;
echo " Next 20 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "
Showing results $b to $a of $numrows
";

OMG, where to start?
Firstly, you're not processing $s at the beginning so the LIMIT statement will always 0,20.
Try something like:
if (isset ($_GET['page']) ){
$s=round($_GET['page'];
if($s<0) {
$s=0;
}
}
else {
$s=0;
}
...
$query .= " LIMIT ".($s*$limit).",$limit";
Then you need to add links the previous and next text:
if ($s>0) { // bypass PREV link if s is 0
echo 'Prev ';
}
...
echo echo 'Next ';
...
To be honest, I'd start again from scratch if I was you, the code is very messy. Write pseudo-code to plan the logic first, then code.

Your "next 20" and "prev 10" are simply text displays. They are not links to begin with. Further more you have no way of handling input. It appears your example is incomplete.

Related

Add pagination to my search engine

How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md

Pagination not showing results on next page

Looking for some help please. I am using the following code to filter and show results which works fine. My problem is the results aren't passing on to the second page so the page becomes blank no errors. very new to this so all help is welcome.
$num_rec_per_page=2;
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("searchresults") or die("ERROR");
if (!isset($_POST['submit'])) exit();
$vars = array('companyname','location');
$verified = TRUE;
foreach ($vars as $v) {
if (!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if (!$verified) {
echo "Sorry no results found, please enter your search";
exit();
}
// isset function is also used in checking for the existence of data in $_POST
if (isset($_POST["companyname"]) && $_POST["companyname"] != '') {
$companyname = mysql_real_escape_string($_POST["companyname"]);
$companyname = " AND (companyname LIKE '%$companyname%')";
}
if (isset($_POST["location"]) && $_POST["location"] != '') {
$location = mysql_real_escape_string($_POST["location"]);
$location = " AND (location LIKE '%$location%')";
}
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location . "LIMIT $start_from, $num_rec_per_page";
$sql_result = mysql_query($sql) or die (mysql_error());
// now echo the code for the table heading
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
}
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location;
$sql_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($sql_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='codetest.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='codetest.php?page=".$i."'>".$i."</a> ";
}
echo "<a href='codetest.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
} else {
echo '<tr><td colspan="5">No results found.</td></tr>';
}

PHP pagination isn't working and I'm not sure why

I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.

Pagination Database Query Woes

I have been working at this all day and still at 8pm have had no luck. I was wondering if you guys can give me some advice on fixing it. I am building an Upload - gif sharing system for University.
Here is my code anyway -
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect("localhost","root","root") or die("Top Query");
mysql_select_db("UPLOAD") or die(mysql_error());
$count_query = mysql_query("SELECT NULL FROM details");
$count = mysql_num_rows($count_query);
//pagination
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#","",$_GET['page']);
}else{
$page= 1;
}
$perPage = 5;
$lastPage = ceil($count / $perPage);
if($page < 1){
$page = 1;
}else if($page > $lastPage){
$page = $lastPage;
}
$limit = "LIMIT " .($page -1) * $perPage . ", $perPage";
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC") or die("2nd Query");
//Puts it into an array
$pagination="";
if($lastPage != 1){
if($page != $lastPage){
$next = $page + 1;
$pagination.='More';
}
if($page != 1){
$prev = $page - 1;
$pagination.='Back';
}
}
?>
And then the output in the html -
<?php
while($info = mysql_fetch_array($query)){
$shortlink = "".$info['photo']." " ;
//Outputs the image and other data
echo "<article class='upload-post'>" . "<div class='crop'>";
echo "<a href=uploads/".$info['photo'].">";
echo "<img class='scale-with-grid' src=uploads/".$info['photo'] .">"."</a>";
echo "</div>";
echo "".$info['name'] . "<br/>";
echo "Reaction ".$info['reaction'] ."<br/>";
echo "In " .$info['category'] ." <br/>";
echo "On " .$info['date_added'] ." <br/>";
echo "Link: $shortlink";
echo "</article>";
}
?>
<?php echo $pagination;?>
I can toggle between pages but its not limiting the number of posts displayed on the page. Id really appreciate the help as the deadline isn't too far away.
Thanks a bunch in advance!
You never append $limit to your query.
Try the follwing as a replacement...
...
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC ".$limit) or die("2nd Query");
//Puts it into an array
...

php search from mysql database showing only one page

The following script is showing only first page and link to next page is there but is not leading anywhere. Can someone help me?
$var = #$_GET['q'] ;
$trimmed = trim($var);
$limit = 10;
if ($trimmed == "")
{
echo "<p>What are you looking for?...</p>";
exit;
}
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
mysql_connect('xxx', 'yyy', 'zzz');
mysql_select_db('yyy') or die('Unable to select database');
$query = "select * from table where NAME like '%$trimmed%' order by NAME";
$numresults = mysql_query($query);
$numrows = mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the search on google</p>";
}
if (empty($s))
{
$s = 0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results";
$count = 1 + $s;
while ($row= mysql_fetch_array($result))
{
$title = $row["NAME"];
echo "$count.- $title" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
echo "<br />";
if ($s >= 1)
{
// bypass PREV link if s is 0
$prevs = ($s - $limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
$pages = intval($numrows/$limit);
if ($numrows % $limit)
{
$pages++;
}
if (!((($s+$limit)/$limit) == $pages) && $pages != 1)
{
$news = $s + $limit;
print "Next 10 >>";
}
$a = $s + ($limit);
if ($a > $numrows)
{
$a = $numrows;
}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
In your code, $s gets reset every time the page is reloaded or the next page link is clicked. You should have $s = $_REQUEST['s'] at the beginning of your code.
PHP_SELF is a $_SERVER variable. Regardless, you should use $_SERVER['SCRIPT_NAME'] here.
echo "Next 10 >>";
Among a few notable improvements, you should really look into sanitizing the variables you put in the querystring with urlencode() as well.

Categories