I have created a search function for the products on my site and I tried to put in pagination so that it is not just a big long list of results. So I started off with something like this:
**Note: I just replaced $_GET['search_term'] with 'whatever' just for this example, and where I have var_dump() I have a function that displays the products for each id in the array it is given.
$term = 'whatever'; //$_GET['search_term'];
$new_term = '%'.$term.'%';
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 1;
}
$per_page = 20;
$last_page = ceil($resultCount/$per_page);
if($page<1){
$page = 1;
}else if($page>$last_page){
$page = $last_page;
}
$pagination = "";
$limit = "LIMIT ".($page-1)*$per_page.",".$per_page;
if($last_page!=1){
if($page!=1){
$prev = $page-1;
$pagination .= "<a class='pagination' href='store'><<</a>";
$pagination .= "<a class='pagination' href='store/$prev'><</a>";
}
for($i=$page-2; $i<=$page+2; $i++){
if($i>0 && $i<=$last_page){
if($i == $page){
$pagination .= "<a class='pagination selected'>$i</a>";
}else{
$pagination .= "<a class='pagination' href='store/$i'>$i</a>";
}
}
}
if($page!=$last_page){
$next = $page+1;
$pagination .= "<a class='pagination' href='store/$next'>></a>";
$pagination .= "<a class='pagination' href='store/$last_page'>>></a>";
}
}
if(isset($term)){
echo $pagination;
$ids = [];
$params = [$new_term];
$sql = "SELECT * FROM products WHERE name LIKE ? $limit";
$stmt = DB::run($sql,$params);
$resultCount = $stmt->rowCount();
if($resultCount > 0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["pro_id"];
$params3 = [$id];
$sql3 = "SELECT * FROM products WHERE id=?";
$stmt3 = DB::run($sql3,$params3);
while($row = $stmt3->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
array_push($ids,$id);
}
}
var_dump($ids);
}
echo $pagination;
}
This worked fine, but then I wanted to make it a fuzzy search so I did:
$term = 'whatever'; //$_GET['search_term'];
$new_term = '%'.$term.'%';
$params = [$new_term];
$sql = "SELECT * FROM products WHERE name LIKE ?";
$stmt = DB::run($sql,$params);
$resultCount = $stmt->rowCount();
if($resultCount < 1){
$sql = "SELECT * FROM products";
$stmt = DB::run($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["pro_id"];
$result = $row[$lang];
similar_text($term,$result,$similarity);
$similar_array[$similarity][] = $id;
}
$closest_match = array_keys($similar_array);
rsort($closest_match);
$match_count = count($closest_match);
$similar_ids = [];
for($i=0; $i<$match_count; $i++){
foreach($similar_array[$closest_match[$i]] as $id){
array_push($similar_ids,$id);
}
}
$resultCount = count($similar_ids);
}
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 1;
}
$per_page = 20;
$last_page = ceil($resultCount/$per_page);
if($page<1){
$page = 1;
}else if($page>$last_page){
$page = $last_page;
}
$pagination = "";
$limit = "LIMIT ".($page-1)*$per_page.",".$per_page;
if($last_page!=1){
if($page!=1){
$prev = $page-1;
$pagination .= "<a class='pagination' href='store'><<</a>";
$pagination .= "<a class='pagination' href='store/$prev'><</a>";
}
for($i=$page-2; $i<=$page+2; $i++){
if($i>0 && $i<=$last_page){
if($i == $page){
$pagination .= "<a class='pagination selected'>$i</a>";
}else{
$pagination .= "<a class='pagination' href='store/$i'>$i</a>";
}
}
}
if($page!=$last_page){
$next = $page+1;
$pagination .= "<a class='pagination' href='store/$next'>></a>";
$pagination .= "<a class='pagination' href='store/$last_page'>>></a>";
}
}
if(isset($term)){
echo $pagination;
$ids = [];
$params = [$new_term];
$sql = "SELECT * FROM products WHERE name LIKE ? $limit";
$stmt = DB::run($sql,$params);
$resultCount = $stmt->rowCount();
if($resultCount > 0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["pro_id"];
$params3 = [$id];
$sql3 = "SELECT * FROM products WHERE id=?";
$stmt3 = DB::run($sql3,$params3);
while($row = $stmt3->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
array_push($ids,$id);
}
}
var_dump($ids);
}else{
var_dump($similar_ids);
}
echo $pagination;
}
There was probably a much better way of doing this but this is what I have. My question then is how can I get the pagination to work here for the fuzzy results ($similar_ids)? I was thinking of some sort of function that will splice the array depending on the page number but I am not sure how I would go about this.
This does not answer your question, but I'm going to say these anyway:
Looking closely, you have a possible sql injection bug in handling of $limit.
Also, using a search index like Apache Solr or ElasticSearch would give you pagination nearly for free anyway. You might want to look into that. Setting up a dedicated index is another can of worms, yes, but then you would also have more and better options to handle that fuzzy search part too.
Related
I have a little script that have a Previous & Next button.
My problem is I want to detect & place the ID in those buttons
this is the code from the pagination
<body>
<?php include_once 'data.php'; ?>
<center>
<ul class="pagination">
<?php
if($page_counter == 0){
echo "<li><a href=?start='0' class='active'>0</a></li>";
for($j=1; $j < $paginations; $j++) {
echo "";
}
}else{
echo "<a href=?start=$previous><button>Previous</button></a>";
for($j=0; $j < $paginations; $j++) {
if($j == $page_counter) {
echo " ";
}else{
echo " ";
}
}if($j != $page_counter+1)
echo "<a href=?start=$next><button>Next</button></a>";
}
?>
</ul>
</center>
In this part I have the ID but the problem is I can`t get it with this example to place it into the pagination.
<?php
foreach($result as $row) {
echo '
<div class="card"><button1>
'. $row['notice_id'] .'
<div class="time-left">
<div class="dropdown1">
' ;
}
}
else {
echo '';
}
$conn->close();
?>
</div></div>
This is the code from data.php I think I need to place some code into for detection from the ID
<?php
//include configuration file
require 'configuration.php';
$start = 0; $per_page = 1;
$page_counter = 0;
$next = $page_counter + 1;
$previous = $page_counter - 1;
if(isset($_GET['start'])){
$start = $_GET['start'];
$page_counter = $_GET['start'];
$start = $start * $per_page;
$next = $page_counter + 1;
$previous = $page_counter - 1;
}
// query to get messages from messages table
$q = "SELECT * FROM group_notice LIMIT $start, $per_page";
$query = $db->prepare($q);
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
// count total number of rows in students table
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
// calculate the pagination number by dividing total number of rows with per page.
$paginations = ceil($count / $per_page);
?>
You can use some formulas for calculate limit and offset of results.
For example you have 100 records, and you want to paginate it into 10 records per page, and the formula is like below.
// Get Page from Query String
$page = 1;
if(!empty($_GET["page"])){
$page = $_GET["page"];
}
// Get record count
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
$per_page = 10; // records per page
$pages = ceil($count/$per_page); // get total page
$start = $page * $per_page - $per_page; // get offset
// Do something with your records
$query = db->prepare("SELECT * FROM group_notice LIMIT ?, ?");
$query->bind_param("ii", $start, $per_page); // you should use bind param if you use prepared statement
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
if($page > 1){
echo 'Prev'; // Print Prev Page
}
for($i = 1; $i <= $pages){
echo ''.$i.''; // Print Page Number
}
if($page < $pages){
echo 'Next'; // Print Next Page
}
Hope it helps.
Am new to php programming and I have written my php code to search data from database then displays it with pagination links for easy navigation in the event that the search result will be too many. But the pagination links will not show because of the above warning. The query is not producing the Count result to make my $limit variable true thereby displaying the first page only. This is the code below, Please can you help me correct the error so that the pagination links show.
<?php
include_once("dbconnect.php");
if(isset($_GET["search"]))
{
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE '%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ."GROUP BY stockID";
$query = mysqli_query($dbconnect, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 12;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE
'%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql= "SELECT * FROM stock WHERE " . $condition."
ORDER BY stockID ASC $limit";
$query = mysqli_query($dbconnect, $sql);
$textline1 = "(<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
$search_query = $_GET['search'];
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$previous.'&search='.$search_query.'">Previous</a> ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'">'.$i.'</a> ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'&search='.$search_query.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a href="'.$_SERVER['PHP_SELF'].'?
pn='.$next.'&search='.$search_query.'">Next</a> ';
}
}
$list = '';
$lists = '';
while($row = mysqli_fetch_array($query)){
$id = $row["stockID"];
$name = $row["stockName"];
$image = $row["thumbnail"];
$description = $row["description"];
$topline = $row['topline'];
$lists .= '<div class="col-md-3" style="margin-bottom:10px;">
<div class="panel panel-info"><a href="index.php?
page=item&stockID='.$id.'&sub_category=">
<div class="panel-body">
<img class="img-responsive" style="height:100px;"
src="resources/stocks_images/'.$image.'" />
</div>
<div class="panel-footer" style="height:100px;">'.$name.'
</div></a>
</div>
</div>';
}
}
mysqli_close($dbconnect);
?>
$dbconnect is undefined in your script. Also rewrite your query:
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ." GROUP BY stockID"; I have added a space just before "Group By". Hope this will help.
I have a php pagination page with post submit by user to search something, query mysql in first page is ok, but in NEXT page, i have get white blank page.
Below is the paging code.
$_SESSION['nationality'] = $_POST['nationality'];
$reclimit = 2;
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$start = (($page-1) * $reclimit);
$sql = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%'";
$records = $con->query($sql);
$total = $records->num_rows;
$tpages = ceil($total / $reclimit);
$rec = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%' LIMIT $start, $reclimit";
$records = $con->query($rec);
while ($row = mysqli_fetch_assoc($records)){
// Loop record
}
// Paging
echo '<ul class="pagination pagination-lg">';
for( $i=1; $i <= $tpages; $i++ ) {
$active = $i == $page ? 'class="active"' : '';
echo "<li $active ><a href='$_SERVER[PHP_SELF]?page=" .$i. "'>" .$i. "</a></li>";
}
echo '</ul>';
This works for me:
<?php
$limit =3;
if (!isset($_GET['pg'])) {
$pg = 1;
} else {
$pg = $_GET['pg'];
}
$start = ($pg - 1 ) * $limit;
$sql = "SELECT * FROM tableName LIMIT $start , $limit";
?>
Can anyone point me out why my pagination is not working, What I am doing wrong here ? Working on it for a long time. my url generates like : http://localhost/medapp/admin/medorder.php?page=%209.
<?php
//pagination
$perpage = 3;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1)*$perpage;
//pagination
$medorder = "SELECT * FROM `medorder` WHERE status='1' order by ID desc";
$result = $db->select($medorder);
if($result){
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$row["uid"]."</td>";
echo "<td>".$row["fullname"]."</td>";
echo "</tr>";
}
// pagination
$query = "select * from medorder";
$result = $db->select($query);
$total_rows = mysqli_num_rows($result);
$total_pages = ceil($total_rows/$perpage);
echo "<span class='pagination'><a href='medorder.php?page=1'>".'First Page'."</a>";
for ($i=1; $i <= $total_pages; $i++) {
echo "<a href='medorder.php?page=".$i."'>".$i."</a>"; }
echo "<a href='medorder.php?page=$total_pages'>".'Last Page'."</a></span>";
//pagination
}
?>
Change your query like this by using LIMIT and OFFSET
$medorder = "SELECT * FROM `medorder` WHERE status='1' order by ID desc LIMIT $start_from,$perpage"; //
in this following line, you have a space before the $i variable:
echo "<a href='medorder.php?page= ".$i."'>".$i."</a>";
should be
echo "<a href='medorder.php?page=".$i."'>".$i."</a>";
I used this code in my all pages. Everywhere this code work well. In case of my search page this code count all page by search words but when I click next(2nd or 3rd) page, its cannot display any item. That means sql query for 2nd or 3rd or any others pages not worked. No error also. Pagination page url goes well also.
My Search code:
if(isset($_POST['searchword'])){
$w = mysqli_real_escape_string($dbh, $_POST['searchword']);
$q = strip_tags($w);
$q = trim ($w);
$limit = 12;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE) ORDER BY id ASC LIMIT $start_from, $limit";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
if ($rowcount > 0 ) {
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
$detail = $row['detail'];
$url = $row['url'];
echo $detail;
}
}
}
//Pagination
$sql = "SELECT COUNT(id) FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE)";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
if($total_records > 0){$total_pages = ceil($total_records / $limit); }
$pagLink = "<ul class='pagination'>";
if(!empty($total_pages)){for ($i=1; $i<=$total_pages; $i++) {
$pagLink .= "<li><a href='".$thispage."?page=".$i."'>".$i."</a> </li>";
};
echo $pagLink . "</ul>";
}