I have a bit of code that pulls all the results from a database and displays the ones that are relevant to the users search. I have some more code that counts the amount of items and generates a certain amount of pages based on how many items are relevant to the users search. The problem is as follows. If I do a search all, my code displays everything in the database on 11 pages. If I search for car, it will still display 11 pages but only 2 results that have the word car in the title. The problem is that these results display on the eighth page and all other pages are blank. During the search all the two results with car in the title displayed on the eighth page as well. The search all is based on the order the items are in, in the database. Here is my current code:
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`)");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$url = "articles/".$ID."/".$donetitle."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
}else{
$donedesc1 = $desc;
}
$finviews = number_format($views, 0, '.', ',');
//Give relevant results
if(stripos($title, $terms) !== false || stripos($desc, $terms) !== false || stripos($username1, $terms) !== false){
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
}
$totalPages = $pageNum;
$currentPage = $page;
$numPagesToShow = 10;
if($currentPage > $totalPages) {
$currentPage = $totalPages;
}
if($numPagesToShow >= $totalPages) {
$numMaxPageLeft = 1;
$numMaxPageRight = $totalPages;
} else {
$pagesToShow = ceil($numPagesToShow/2);
$numMaxPageLeft = $currentPage - $pagesToShow;
$numMaxPageRight = $currentPage + $pagesToShow;
if($numMaxPageLeft <= 0) {
$numMaxPageRight = $numMaxPageRight - $numMaxPageLeft +1;
$numMaxPageLeft = 1;
} elseif($numMaxPageRight >= $totalPages) {
$numMaxPageLeft -= ($numMaxPageRight - $totalPages);
$numMaxPageRight = $totalPages;
}
}
for ($i=$numMaxPageLeft; $i<=$numMaxPageRight; $i++) {
echo "<a id =\"pagenationlink\" href=\"searchresults.php?search=".$terms."&page=".$i."\">".$i."</a>";
}
How can I only display one page with the two results on it instead of 11 pages with the two relevant results on the eighth page? Thanks
Please update your code as below.
But try to use mysqli_() as mysql() are depricted
$cond = "";
if(!empty($_POST["search"]))
{
$cond = " write your search condition " ;
}
$start = (($page-1)*5);
$query = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM posts where $cond LIMIT $start, 5");
$TotalDataQuery = mysql_query("SELECT FOUND_ROWS() tot;");
$rsVal = mysql_fetch_array($pagesQuery);
$pagesQuery = $rsVal['tot'];
$pageNum = ceil($pagesQuery/5);
while ($row = mysql_fetch_array($query)) {
//continue your code
}
Related
I need some help, I want to make an next / previous page but I have some problems...
This is the PHP Code, how I try to make it. The problem is that it doesn't show 3 data on the first page and on the next page it puts the same data again an not the other one.
Code:
$statement = $connect->prepare("SELECT COUNT(*) AS anzahl FROM `accounts`");
$statement->execute();
$row = $statement->fetch();
$max_data = $row['anzahl'];
$page = 1;
if(isset($_GET['page'])) {
$page = intval($_GET['page']);
}
$max_info = 3;
$start = ($page - 1) * $max_info;
$number_page = ceil($max_data / floatval($max_info));
for($a = 1; $a <= $anzahl_seiten; $a++) {
if($page == $a){
echo " <b>$a</b> ";
}
else {
echo " <a href='acp.php?page=list_all_player&seite=$a'>$a</a> ";
}
}
I have some PHP and html code that loads in results from my database. It shows five results per page. Let's pretend I have 1000 pages. The links for all those pages would go off the screen. Google had this problem but they fixed it by only displaying the current link as well as 5 links back and 5 links forward. I want to do something like this. I don't want to display 100 links to the various pages. Pretend the user is on page 100. I want to display the links for page 100 as well as link 95 to 105. How can I do this? Here is my code so far:
$page = $_GET["page"];
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`)");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$url = "articles/".$ID."/".$donetitle."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
}else{
$donedesc1 = $desc;
}
$finviews = number_format($views, 0, '.', ',');
//Give relevant results
if(stripos($title, $terms) !== false || stripos($desc, $terms) !== false || stripos($username1, $terms) !== false){
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
}
for ($j=1; $j < $pageNum; $j++) {
echo "<a id =\"\" href=\"searchresults.php?search=".$terms."&page=".$j."\">".$j."</a>";
}
What you want is to change this:
for ($j=1; $j < $pageNum; $j++) {
echo "<a id =\"\" href=\"searchresults.php?search=".$terms."&page=".$j."\">".$j."</a>";
}
Here you list all links $j < $pageNum and you want to list just 10: $j <= 10 starting $j = $currentPage or $j = $currentPage - 5 if $currentPage is > 5
I have a piece of PHP code that is supposed to loop through all the results and make a new page for every 10 results, however it only shows the first 10 results and no options of next page or page numbers.
Is there a reason for this or have I missed something in the code I have written?
Thanks in advance.
My code is below;
$search_course = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$search_result = $result->fetch_assoc();
$row = mysqli_fetch_row($result);
//total rows for search
$rows = $row[0];
//number of results per page
$rows_per_page = 10;
//shows last page
$last_page = ceil($rows/$rows_per_page);
if($last_page < 1){
$last_page = 1;
}
$page_number = 1;
if(isset($_GET['pn'])){
$page_number = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
//makes sure page number is between limits of $page_number
if($page_number < 1){
$page_number = 1;
} else if($page_number > $last_page){
$page_number = $last_page;
}
// sets the value of items to view
$limit = 'LIMIT ' .($page_number -1) * $rows_per_page .',' .$rows_per_page;
// query again only grabbing the set number of rows depending on page number
$search_course = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'
ORDER BY title DESC $limit";
$result = $mysqli->query($search_course) or die($mysqli->error);
$search_result = $result->fetch_assoc();
//displays to the user the total number of results and the page numbers
$total_number_of_results = "Search Results (<b>$rows</b>)";
$page_user_is_on = "Page <b>$page_number</b> of <b>$last_page</b>";
//set up pagination
$pagination_controls = '';
if($last_page != 1){
if($page_number > 1){
$previous = $page_number - 1;
$pagination_controls .='previous ';
for($i = $page_number - 4; $i < $page_number; $i++)
{
if($i > 0){
$pagination_controls .= ''.$i.' ';
}
}
}
$pagination_controls.=''.$page_number.' &nbsm; ';
//clickable links to the left
for($i = $page_number+1; $i <= $last_page; $i++)
{
$pagination_controls .= ''.$i.' ';
if($i >= $page_number+4){
break;
}
}
if($page_number != $last){
$next = $page_number + 1;
$pagination_controls.=' Next';
}
}
$list = '';
while($row = mysqli_fetch_array($result)){
$title = $row['title'];
$id = $row['id'];
$list.='<p><a href="Selectedcourse.php">'.$title.' </p>';
}
mysqli_close($mysqli);
and the html element;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='courses.css'>
</head>
<body>
<div class="header">
<h1>Search Results for - <?= $_POST['searchBar'] ?></h1>
</div>
<div>
<h3> <?php echo $page_user_is_on ?> </h3>
<p><?php echo $list; ?></p>
<p><?php echo $search_result['summary']; ?> </p>
</div>
<div id="pagination_controls"><?php echo $pagination_controls; ?></div>
</body>
</html>
This is a good effort to roll your own pagination. It was mostly working. The problem was in your first query here:
$search_result = $result->fetch_assoc();
//This fetches only the first row of results
$row = mysqli_fetch_row($result);
//So this is not the total rows for search
$rows = $row[0];
Here's an updated script using prepared statements, which you really need to use. Unless you love being hacked.
//turn errors on to develop, back off when you go live
error_reporting(E_ALL);
ini_set('display_errors', 1);
//here are my main changes
$search_param = "%" . $_POST['searchBar'] . "%";
$stmt = $mysqli->prepare("SELECT title, summary, id FROM course WHERE title LIKE ?");
$stmt->bind_param("s", $search_param); //learn this
$stmt->execute();
$result = $stmt->get_result();
//This gets the number of rows in a query result
$rows = $result->num_rows;
//number of results per page
$rows_per_page = 10;
//shows last page
$last_page = ceil($rows/$rows_per_page);
if($last_page < 1){
$last_page = 1;
}
if(isset($_GET['pn'])){
$page_number = preg_replace('#[^0-9]#', '', $_GET['pn']);
} else {
$page_number = 1;
}
//makes sure page number is between limits of $page_number
if($page_number < 1){
$page_number = 1;
} else if($page_number > $last_page){
$page_number = $last_page;
}
// sets the value of items to view
$limit = 'LIMIT ' .($page_number -1) * $rows_per_page .',' .$rows_per_page;
//displays to the user the total number of results and the page numbers
$total_number_of_results = "Search Results (<b>$rows</b>)";
$page_user_is_on = "Page <b>$page_number</b> of <b>$last_page</b>";
//query again only grabbing the set number of rows depending on page number
$stmt = $mysqli->prepare("SELECT title, summary, id FROM course WHERE title LIKE ? ".$limit);
$stmt->bind_param("s", $search_param);
$stmt->execute();
$result = $stmt->get_result();
$list = '';
while($row = $result->fetch_assoc()){
$title = $row['title'];
$id = $row['id'];
//I'm assuming you want each link to be different here...
$list.='<p>' . $title . '</p>';
}
mysqli_close($mysqli);
//set up pagination
$pagination_controls = '';
if($last_page != 1){
if($page_number > 1){
$previous = $page_number - 1;
$pagination_controls .='previous ';
for($i = $page_number - 4; $i < $page_number; $i++)
{
if($i > 0){
$pagination_controls .= ''.$i.' ';
}
}
}
$pagination_controls.=''.$page_number.' ';
//clickable links to the left
for($i = $page_number+1; $i <= $last_page; $i++)
{
$pagination_controls .= ''.$i.' ';
if($i >= $page_number+4){
break;
}
}
if($page_number != $last_page){
$next = $page_number + 1;
$pagination_controls.=' Next';
}
}
And finally the HTML section, with only one change:
<div class="header">
<h1>Search Results for - <?= $_POST['searchBar'] ?></h1>
</div>
<div>
<h3> <?php echo $page_user_is_on ?> </h3>
<p><?php echo $list; ?></p>
<p><?php /* echo $search_result['summary']; //Where was this coming from? */?> </p>
</div>
<div id="pagination_controls"><?php echo $pagination_controls; ?></div>
I have the following mysql query and I have added pagination from here:
http://www.tonymarston.net/php-mysql/pagination.html
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
if (mysqli_num_rows($DBQuery3) < 1) {
$ProjectContent = '
<p>This project is empty. Upload some files to get started.</p>
';
} else {
//if no page number is set, start at page 1
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//This code will count how many rows will satisfy the current query.
$DBQuery3b = mysqli_query($dblink, "SELECT count(*) FROM images WHERE project_id = '$FormProjectID'");
$query_data = mysqli_fetch_row($dblink, $DBQuery3b);
$numrows = $query_data[0];
//This code uses the values in $rows_per_page and $numrows in order to identify the number of the last page.
$rows_per_page = 2;
$lastpage = ceil($numrows/$rows_per_page);
//This code checks that the value of $pageno is an integer between 1 and $lastpage.
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
//This code will construct the LIMIT clause for the sql SELECT statement.
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$DBQuery3c = "SELECT * FROM images WHERE project_id = $FormProjectID $limit";
$DBQuery3d = mysqli_query($dblink, $DBQuery3c);
//set this variable to empty and so we can latwe loop and keep adding images to it
$ProjectContent ='';
while($row = mysqli_fetch_array($DBQuery3d)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBLinkToThumb = $row['link_to_thumbnail'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$ProjectContent .= '
<img src="uploads/'.$DBLinkToThumb.'" width="150px" height="150px" alt="'.$FileName.'" title="'.$FileName.'"/>
';
//Finally we must construct the hyperlinks which will allow the user to select other pages. We will start with the links for any previous pages.
if ($pageno == 1) {
$FirstPrev = " FIRST PREV ";
} else {
$First = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=1'>FIRST</a> ";
$prevpage = $pageno-1;
$Prev = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$prevpage'>PREV</a> ";
}
//Next we inform the user of his current position in the sequence of available pages.
$PageNumb = " ( Page $pageno of $lastpage ) ";
//This code will provide the links for any following pages.
if ($pageno == $lastpage) {
$NextLast = " NEXT LAST ";
} else {
$nextpage = $pageno+1;
$Next = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$nextpage'>NEXT</a> ";
$Last = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$lastpage'>LAST</a> ";
}
}
}
Then in my html I have:
<div id="projectview">
<?php echo $ProjectContent; ?>
<?php echo $FirstPrev; ?>
<?php echo $First; ?>
<?php echo $Prev; ?>
<?php echo $PageNumb; ?>
<?php echo $NextLast; ?>
<?php echo $Next; ?>
<?php echo $Last; ?>
<div class="clear-div"></div>
</div>
This is outputing for example in this case 2 images, but the pagination links look like this:
FIRST PREV ( Page 1 of 0 ) NEXT LAST
Clicking on the links is not cycling through any other images, it still shows the same 2 images.
I can't figure out what I have done wrong here. I don't understand why it says "1 of 0" when clearly there should be more results.
I am doing my first pagination implementation to my site. I feel like I am very close and just confusing my logic or mistaking the placement or actual value of some variables.
Here is the code:
$pgsize_wave = 40;
$pg_wave = (is_numeric($_GET["p"]) ? $_GET["p"] : 1);
$start = ($pg_wave-1)*$pgsize_wave;
$waves = mysql_query("SELECT * FROM `CysticAirwaves` LIMIT $start, $pgsize_wave");
$waves_total = mysql_query("SELECT COUNT(1) FROM `CysticAirwaves`");
$waves_total = mysql_fetch_row($waves_total);
$waves_total = $waves_total[0];
$max_pages = $waves_total / $pgsize_wave;
$max_pages = ceil($waves_total/$pgsize_waves);
?>
<div id="all_page_turn">
<ul>
<?php if($waves_total > 40 && $pg_wave >= 40) { ?>
<li class="PreviousPageBlog round_10px">
Previous Page
</li>
<?php } ?>
<?php if($waves_total > 40 && $pg_wave < ($waves_total-40)) { ?>
<li class="NextPageBlog round_10px">
Next Page
</li>
<?php } ?>
</ul>
</div>
To clarify any confusion, an airwave is a post from a user and I want to limit 40 per page. If it helps here is the query that pulls an airwave on the same page:
$query = "SELECT * FROM `CysticAirwaves` WHERE `FromUserID` = `ToUserID` AND `status` = 'active' ORDER BY `date` DESC, `time` DESC";
$request = mysql_query($query,$connection);
$counter = 0;
while($result = mysql_fetch_array($request)) {
$replies_q = "SELECT COUNT(`id`) FROM `CysticAirwaves_replies` WHERE `AirwaveID` = '" . $result['id'] . "' && `status` = 'active'";
$request2 = mysql_query($replies_q,$connection);
$replies = mysql_fetch_array($request2);
$replies_num = $replies['COUNT(`id`)'];
$counter++;
$waver = new User($result['FromUserID']);
Thanks so much in advance.
This is pseudo code but hopefully explains the logic.
$total = SELECT COUNT(*) FROM `waves`
$currentPage = 1 // changes through page parameter in URL
$wavesPerPage = 40
$totalPages = ceil($total / $wavesPerPage)
$offset = ($wavesPerPage * ($currentPage - 1)) + 1
$waves = mysql_query("SELECT * FROM `waves` LIMIT $offset, $wavesPerPage");
while ($row = mysql_fetch_assoc($waves)) {
echo $row['wave']
…
}
To output the pagination links:
if ($totalPages > 1) {
if ($currentPage > 1) {
printf('Previous', $currentPage - 1);
}
for ($i = 1; $i <= $totalPages; $i++) {
$class = ($i == $currentPage) ? 'selected' : null;
printf('Page %1$u', $i, $class);
}
if ($currentPage < $totalPages) {
printf('Next', $currentPage + 1);
}
}