As the data has grown the need for pagination is of great importance. Everything works fine. I have a limit in my SELECT statement and count the rows. The goal is to have pagination at the bottom of the page with the limit of 10. The page contains the latest rows in the database. Do i need to have
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$nr = 0;
$count = mysql_query("SELECT count(*) AS TOTAL FROM quotes");
$row = mysql_fetch_array($sum);
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$output = "";
while($row = $result->fetch_assoc() ) {
$topic = trim($row["topic"]);
$quote = trim($row["quote"]);
$author = trim($row["author"]);
$id = trim($row["id"]);
$output .= injectNColumnWrapper(3, $nr, "container row", $nr);
$output .="<div class='col s12 m6 l4 z-depth-1'>";
$output .="<div class='card-panel grey darken-4 white-text center'>";
$output .=" <h5>Citat: {$id}</h5>";
$output .="</div>";
$output .="<pre class='flow-text black-text' wrap='soft'>";
$output .="<p class='flow-text-p citat'>"{$quote}"</p>";
$output .="<p style='font-weight:bold; class='flow-text-p author'>{$author}</p>";
$output .="<p class='flow-text-p topic'>{$topic}</p>";
$output .="</pre>";
$output .="<div class='content_wrapper'>";
$output .="<h4></h4>";
$output .="<div class='voting_wrapper' id='vote-{$id}'>";
$output .="<div class='voting_btn'>";
$output .="<div class='up_button'> </div>";
$output .="<span class='up_votes'>0</span>";
$output .="</div>";
$output .="<div class='voting_btn'>";
$output .="<div class='down_button'> </div>";
$output .="<span class='down_votes'>0</span>";
$output .="</div>";
$output .="<br>";
$output .="</div>";
$output .="</div>";
$output .="</div>";
$nr++;
}
$output .= "</div>";
echo $output;
}else {
echo "0 results";
}
$conn->close();
function injectNColumnWrapper($cols_per_row, $closePoint, $cssClass="container row", $nthElem=""){
$blockDisplay = "";
if( ($closePoint == 0) ){
$blockDisplay = "<div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}else if( ($closePoint % $cols_per_row) == 0 && ($closePoint != 0) ){
$blockDisplay = "</div><div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}
return $blockDisplay;
}
?>
$limit = 10;
$start = $nr * $limit
$sql = "SELECT * FROM quotes ORDER BY date DESC limit $start $limit";
Where $nr is number of current page -1, so if you have page 1, it should be 0, if 2 then 1, etc.
To get number of pages, you ned to take all your results count and make division by limit so for example 100/10 = 10 pages. Simple for loop should render pages.
Use offset in your query.
You may display a set of links in your pagination, then catch the param from the URL and finally construct the query with the proper offset.
Pagination links:
// Note: $row['TOTAL'] comes from your counting sql (count(*))
for ($i = 0; $i< $row['TOTAL']; $i++) {
echo " <a href='?p=$i'>$i</a> |";
}
Get the requested page in your URL:
$requestedPage = !empty($_GET['p']) ? intval($_GET['p']) : 0;
Construct the query:
$pagination = 10 * $requestedPage;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10 OFFSET $pagination";
You should give start and length (offset) values to limit data in MySQL for pagination. EG :
SELECT * FROM table_name WHERE your_condition LIMIT 0,9 - to fetch first 10 records
SELECT * FROM table_name WHERE your_condition LIMIT 10,19 - to fetch second set of 10 records
Refer for example. And it is a duplicate question
Related
I'm trying to build a demo website showcasing the food and/or products in your home ie. fridge or freezer.
I've got most of it down, dynamically creating a list with the items, but I would like to have the duplicates count up like 1x [product] instead of just appearing multiple times in the list like this:
.
My query and stuff looks like this - all inside a for loop.
$sql = "SELECT * FROM goods WHERE person_id = " . $_SESSION['ID'] . " AND room LIKE '" . $rooms[$count] . "'";
if ($result = mysqli_query($conn, $sql)){
if (mysqli_num_rows($result) > 0){
$output = "<ul>";
while ($row = mysqli_fetch_array($result)){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
}
Hope you can help - I'm not that experienced with PHP :)
Check the following code where I show you how to have a group by to have the quantity per item and also, how to use query with prepared statements to avoid sql injection:
// prepare and bind
$stmt = $conn->prepare("SELECT COUNT(*) AS QUANTITY, * FROM goods WHERE person_id = ? AND room LIKE ? BROUP BY name");
$stmt->bind_param("ii", $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if ($result) {
$output = "<ul>";
while ($row = $stmt->fetch_assoc()) {
$output .= "<li class='varer'> " . $row['QUANTITY'] . "x " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
(using prepared statements)
$sql = "SELECT room,count(*) FROM goods WHERE person_id = ? AND room LIKE ? ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
result = $stmt->get_result();
if( $result->num_rows > 0 ){
$output = "<ul>";
while ($row = $result->fetch_assoc()){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
$stmt->close();
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
How do i add PHP pagination to results coming from search query. I have tried here andhere but didn't seem to get how these works or should work with my code. I have written the search query before i thought of pagination cause i was using the load on scroll before. How do i make the results show paginated.
Below is my code to display searchresults.php.
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
I was using this along side javascript to load more result on scroll
if (isset($_POST['limit']) && isset($_POST['start'])) {
$start = $_POST["start"];
$limit = $_POST["limit"];
$query =<<<EOF
SELECT * FROM questions ORDER BY quiz_id DESC LIMIT '$start', '$limit';
EOF;
// echo $query;
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
echo '<div class="quesbox_2">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
<div class="quesdatetime"><img src="images/questime.png" alt="export question">'.$row["date"].'</div>
</div>';
}
}
How do i add pagination to my searchresults.php?
Thanks.
try this code without using jquery
<?php
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview=10;
if($_GET["pageno"]){
$page=$_GET["pageno"];
}else{
$page=1;
}
$frompage = $page*$perpageview-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order.' LIMIT '.$frompage.','.$perpageview;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++) {
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}
?>
I have a php search script that search and echos out result from database. The issue is that i am trying to paginate the search results but when i click on a different page, it shows the same result. That is the search results are not shared across the pages. Please how do i fix?
Below is my code
if (isset($_GET["mainSearch"]))
{
$condition = '';
$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview = 10;
$page = $_GET["pageno"];
$frompage = $page*$perpageview+1-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++)
{
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}
Thanks very much.
I have mentioned in your previous request check
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview=10;
if($_GET["pageno"]){
$page=$_GET["pageno"];
}else{
$page=1;
}
$frompage = $page*$perpageview-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order.' LIMIT '.$frompage.','.$perpageview;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++) {
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}
Trying to display six of the latest posts from my PhpBB installation. I'm happy with how it's all working, however it's showing six copies of the same (most recent) post, and not size unique latest posts.
Just to confirm, I have seven total posts on the forums.
<?php
$con = mysqli_connect("localhost", "dbuser", "dbpass", "dbname");
$users = mysqli_query($con, "SELECT * FROM phpbb_user_group WHERE group_id='8'");
while($row = mysqli_fetch_array($users)) {
$developers[] = $row["user_id"];
}
$post = mysqli_query($con, "SELECT * FROM phpbb_posts");
while($row = mysqli_fetch_array($post)) {
$topic_id = $row["topic_id"];
$forum_id = $row["forum_id"];
$post_id = $row["post_id"];
$post_text = $row["post_text"];
$post_time = $row["post_time"];
}
$username = mysqli_query($con, "SELECT * FROM phpbb_users WHERE user_id='2'");
while($row = mysqli_fetch_array($username)) {
$postauthor = $row["username"];
if (strlen($post_text) > 10)
$post_text = wordwrap($post_text, 120);
$post_text = explode("\n", $post_text);
$post_text = $post_text[0] . '...';
$result = mysqli_query($con, "SELECT * FROM phpbb_posts WHERE poster_id='2' LIMIT 6");
while($row = mysqli_fetch_array($result)) {
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $forum_id . '&p=' . $topic_id . '#p' . $post_id . '\';" class="forum-latest-box">';
$content .= '<div class="forum-latest-userbar">';
$content .= '<div class="forum-latest-avatar">';
$content .= '<img src="https://minotar.net/helm/' . $postauthor . '/40.png">';
$content .= '</div>';
$content .= '<h1>' . $postauthor . '</h1>';
$content .= '</div>';
$content .= '<div class="forum-latest-content">';
$content .= '<div class="forum-latest-text">';
$content .= '"' . $post_text . '"';
$content .= '</div>';
$content .= '<div class="forum-latest-meta">';
$content .= gmdate("F j, Y, g:i a", $post_time);
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
echo $content;
}
?>
You can solve this problem by using a single loop and getting your post data and user information at the same time using combined query to the phpbb_posts table and phpbb_users table:
## Line break added to the query for legibility
$result = mysqli_query($con,
"SELECT
p.post_id AS post_id,
p.topic_id AS topic_id,
p.forum_id AS forum_id,
p.post_time AS post_time,
p.post_subject AS subject,
p.post_text AS post_text
IFNULL(m.username, 'Guest') AS username,
FROM phpbb_posts AS p
LEFT JOIN phpbb_users AS m ON (m.user_id = p.poster_id)
ORDER BY phpbb_posts.post_time DESC LIMIT 6");
while($row = mysqli_fetch_array($result)) {
# $row now contains the post information and the user info, so you can grab all your data,
# process the post text, and print it out at the same time.
$post_text = $row["post_text"];
# do your text transformation
if (strlen($post_text) > 10)
... (etc.)
# now set up your content
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $row["forum_id"] .'&p=' . $row["topic_id"] . '#p' . $row["post_id"] . '\';" class="forum-latest-box">';
... (etc.)
}