I've succeeded display the data what I want based on the select box, but why is my pagination not working?
The index.php display with pagination not working
this is my ajax script to load data and pagination function
<div class="col-md-12">
<div class="table-responsive" id="show-level"></div>
</div>
</div>
</body>
</html>
<!---jQuery ajax load rcords using select box --->
<script type="text/javascript">
$(document).ready(function(){
load_data();
function load_data(page){
$(".level").on("change", function(){
var levelname = $(this).val();
if (levelname !== "") {
$.ajax({
url : "display.php",
type:"POST",
cache:false,
data:{levelname:levelname, page:page},
success:function(data){
$("#show-level").html(data);
}
});
}else{
$("#show-level").html(" ");
}
});
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and then this is my display.php where the pagination function is set
$output .= "</table>";
$page_query = "SELECT * FROM list WHERE level = 'sulit'";
$page_result = mysqli_query($con, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
}else{
echo "No records found";
}
?>
If $records_per_page is 10, and the number of total records is 100, the below will always give you the first 10 items.
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++) {
...
You should look at limiting the number of results and offsetting them in your SQL instead. For instance, you can limit your number of rows to 10, and then offset the results by the page number you are currently on (*10).
Here is what the statement would look like for page 2:
SELECT * FROM list WHERE level = 'sulit' LIMIT 10 OFFSET 10
So your code could look something like (I haven't tested this - but I think it should be about right):
$offset = $current_page * $records_per_page;
$page_query = "SELECT * FROM list WHERE level = 'sulit' LIMIT ? OFFSET ?";
$page_result = mysqli_prepare($con, $page_query);
mysqli_stmt_bind_param($page_result, 'ii', $records_per_page, $offset);
mysqli_stmt_execute($page_query);
Related
Used a form to create a php search for a MySQL database in a header.php file.
Attempting to use simplePagination.js with php. I am able to correctly calculate the number of results and display the appropriate amount of page links. However, search.php is not limiting the number of items on the page, and all of the pagination links lead to a blank page.
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
search.php code:
<?php
include 'header.php';
?>
<section class="searchPage">
<div class="searchResults">
<?php
if (isset($_POST['submit-search'])){
$searchTerm = trim( (string) $_POST['search'] );
if (isset( $searchTerm[0] )) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
$limit = 10;
$numberOfPages = ceil($queryResult/$limit);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
$pageLinks = "<nav><ul class='pagination'>";
for ($i=1; $i<=$numberOfPages; $i++) {
$pageLinks .= "<li><a href='search.php?page=".$i."'>".$i."</a></li>";
};
echo $pageLinks . "</ul></nav>";
}
else {
echo "There are no results matching your search.";
}
}
}
?>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'search.php?page='
});
});
</script>
You don't need to create the page links on your own, because this is what the plugin does through JavaScript events. So you can replace the ul with a div element. This is the reason why you get a blank page.
echo "<nav><div class='pagination'></div></nav>";
In the following is what I added to make it work:
$(document).ready(function(){
var pageParts = $(".articleItem");
pageParts.slice(<?php echo $limit;?>).hide();
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
onPageClick: function(pageNum) {
var start = <?php echo $limit;?> * (pageNum - 1);
var end = start + <?php echo $limit;?>;
pageParts.hide().slice(start, end).show();
}
});
});
I Have problem, I have ajax request and php script, when I click button, results duplicate.
HTML AND JS:
$("#more-news").click(function(e) {
e.preventDefault();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "/getnews.php",
dataType: "html", //expect html to be returned
data: {
lang: lng,
last_id: last_id,
ids: dataN
},
success: function(response){
var content = document.getElementById("responsecontainer");
content.innerHTML = content.innerHTML+response;
//$("#responsecontainer").html(response);
$('#more-news').attr('data-lim', Number($('#more-news').attr('data-lim')) + 10);
//alert(response);
}
});
});
<div id="responsecontainer"></div>
<div style="text-align: center;">
<button id="more-news" data-lim="10" style="border:none" class="btn-type-one">
<span class="more"><?= $this->trans->t('More'); ?></span>
</button>
</div>
<?php
$dtTTNews = [];
foreach ($front_page_news as $item) {
$dtTTNews[] = $item['id'];
?>
<? } ?>
<script>
var dataN = <?php echo json_encode($dtTTNews); ?>;
var lng = '<?=$lang?>';
var last_id = '<?=end($dtTTNews)?>';
</script>
PHP:
$ids = $_GET['ids'];
$dtNow = new \DateTime('now');
$db->set_charset("utf8");
$news_id = abs($db->real_escape_string($_GET['last_id']));
$date_now = new \DateTime('now');
$in = join(',', array_fill(0, count($ids), '?'));
//$q = $db->query("select * count(*)
$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
//$q = $db->query('SELECT id, title_ru, title_md, body_ru, body_md, is_video, thumb_ru, thumb_md, date_show,title_ru, title_md
//FROM news GROUP BY id');
$lang = (isset($_GET['lang']) && $_GET['lang'] == 'ru') ? 'ru' : 'md';
$isHidden = false;
if($q->num_rows > 0):
while($item = $q->fetch_assoc()):
$dtNews = new \DateTime($item['date_show']);
if ($dtNews > $dtNow) {
$isHidden = true;
break;
}
$qs = $db->query("SELECT * FROM news_categories WHERE news_id = " . $item['id']);
if($qs->num_rows > 0) {
$dd = $qs->fetch_assoc();
$qss = $db->query("SELECT * FROM categories WHERE id = " . $dd['categories_id']);
$dd2 = $qss->fetch_assoc();
if(in_array('Скрытые новости', $dd2) || in_array('Hidden News', $dd2)) {
$isHidden = true;
break;
}
}
$dtShow = $dtNews->format("Y-m-d");
//$dtShow = \Noitools\Utils::timeFromPost($item['date_show'], $lang);
if($item['active'] == '1'):
if($item['body_' . $lang] != ''):
if(!$isHidden):
?>
<div class="article-item" data-news="<?= $item['id']; ?>">
<a href="/<?=$lang?>/news_id/<?=$item['id']?>"
class="link-img-wrap<?= ($item['is_video']) ? ' video-icon-medium' : ''; ?>">
<img src="/uploads/newsthumbs/760_500/<?=$item['id']?>.jpg"
alt="">
</a>
<div class="details-post">
<i><?=$dtShow?></i>
<?= $dd2['title_' . $lang] ?>;
</div>
<h3><a href="/<?=$lang?>/news_id/<?=$item['id']?>"><span
class="detail-title"><?=$dtShow?></span> <?= $item['title_' . $lang] ?></a></h3>
<p class="small-text">
<?= mb_substr(strip_tags($item['body_' . $lang]), 0, 180,
'utf-8') ?>
</p>
</div>
<?php endif; endif; endif; endwhile; endif; ?>
How I Can Fix this duplicates? I think, because LIMIT 3, when I click button he load 3 same elements ..
I want when I click button more, load 3 more news
On first glance it appears that the problem lies with you SQL statement:
$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
Since you are appending the Ajax results each time, you only want to fetch news results that you haven't fetched before. By using less than, you are fetching ALL results less than $news_id, each time.
What you need to do is to window your results. In other words, you need to have a starting id and then fetch several more records. So:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
And as long as you keep passing the new id (last_id in your javascript), as the last record fetched, it should work.
The other problem you may have is your ordering. You need to order the same way that you are comparing. If comparing by id, you need:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY id ASC LIMIT 3');
If comparing by date then something like:
$q = $db->query('SELECT * FROM news WHERE date_show < "'.$date_show.'" ORDER BY date_show DESC LIMIT 3');
You can't mix both id and date_show. Unless you know that id and date_show are strictly in the same order.
I am trying to refresh/update the contents of multiple divs on the same page. I have a code I have been working with which works great for a single div but, I need to be able to refresh/update the content of multiple divs. The data is coming from a database. Here is an example of how that works.
data.php
<?php
include('dbconn.php');
$sql = "SELECT gpsStatus FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$gpsStatus[$i] = $row["gpsStatus"];
$i++;
}
}
$sql = "SELECT DisplayName FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$DisplayName[$i] = $row["DisplayName"];
$i++;
}
}
$sql = "SELECT ChaserLocation FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$chaserLocation[$i] = $row["ChaserLocation"];
$i++;
}
}
$sql = "SELECT StreamStatus FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$status[$i] = $row["StreamStatus"];
$i++;
}
}
$sql = "SELECT TimeStamp FROM streamdb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while($row = $result->fetch_assoc()) {
$timeStamp[$i] = $row["TimeStamp"];
$i++;
}
}
$conn->close();
<div class="left"><h3 class="panel-title"><?php if ($gpsStatus[1] == 'true' ) { echo "<i class='small material-icons' style='color:#00FF00; font-size:12px;' title='GPS Location Active'>gps_fixed</i>"; } else { echo "<i class='small material-icons' style='color:#FF0000; font-size:12px;' title='GPS Location Offline'>gps_fixed</i>"; } echo " $DisplayName[1]"; if ($gpsStatus[1] == 'true' ) echo " - $chaserLocation[1]"; ?></h3></div> <div class="right"><h3 class="panel-title"><?php if ($status[1] == 'true' ) { echo "<span class='label label-success' style='vertical-align:-40px;'><i class='fa fa-video-camera'></i> LIVE</span>"; } else { echo "<span class='label label-important'><i class='material-icons' style='vertical-align:-4px; font-size:14px;'>videocam_off</i> OFFLINE</span>"; } ?></h3></div><div style="clear:both;"></div>
Then I have a js file called update.js which looks like this that calls the above file...
$(document).ready( function(){
$('#chaser1').load('inc/data.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#chaser1').load('inc/data.php');
refresh();
}, 2000);
}
Then on my HTML page I call like so which refreshes the div...
<div class="col-md-3"> <div class="panel panel-primary">
<div class="panel-heading">
<div id="chaser1"></div>
</div>
This works great for a single div when the data in the DB updates the div updates but, I am unable to use this to update multiple divs. I have tried adding multiple calls to different files for each file and change the ID but then it only updates the last div. Is there a simplified way to update/refresh the data in multiple divs on the same page with the data from the database. This would work if I loaded all my HTML into the data.php but, the problem then arises that the panel body of the div contains a video player so it refreshes the video player too which is not want I want because this it will stop the player each time it refreshes and updates the divs.
-Thanks
It may not be the prettiest or most logical solution but, it functions as I am needing.
For my update.js I just added each ID like so and pointed each new ID to its own page like so.
$(document).ready( function(){
$('#chaser1').load('inc/chasers/ncopeland.php');
$('#chaser2').load('inc/chasers/ksaunders.php');
$('#chaser3').load('inc/chasers/rcontreras.php');
$('#chaser4').load('inc/chasers/nbusby.php');
$('#chaser5').load('inc/chasers/gyates.php');
$('#chaser6').load('inc/chasers/jcollum.php');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#chaser1').load('inc/chasers/ncopeland.php');
$('#chaser2').load('inc/chasers/ksaunders.php');
$('#chaser3').load('inc/chasers/rcontreras.php');
$('#chaser4').load('inc/chasers/nbusby.php');
$('#chaser5').load('inc/chasers/gyates.php');
$('#chaser6').load('inc/chasers/jcollum.php');
refresh();
}, 2000);
}
Then on the page for each div included the ID like so with the ID corresponding to the data which it is looking for and include all the markup and php on that page it is calling.
<div id="chaser1" class="panel-heading">
</div>
It may not be the most logical but, it appears to be working now.
I am displaying posts in a table and then trying to call more posts using ajax, but I am encountering problems here, on clicking show more same posts appear again so how to call next posts by id, and another problem is on clicking show more it changes to loading and remains their, I want it to hide after posts have been loaded.
I am calling the whole table again I think I would be better to call only rows. Here are my two files
index.php
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
}
});
});
});
</script>
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
<div id="posts">
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
</div>
ajax_more.php
<?php
include('db.php');
if(isset($_POST["id"]) && !empty($_POST["id"])){
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
?>
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
<?php
}
?>
You will have to use OFFSET and LIMIT for your SQL Query. Currently you are using SELECT * FROM posts order by id desc limit 6. That isn't going to load you "more", as it will always only fetch the 6 biggest posts (ordered descending by their id).
You have a couple of problems.
When your AJAX call completes and you want the loading message to disappear, you need to hide that in your success callback of the ajax call. Like so:
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
$('.loding').hide();
}
});
});
In your SQL, you aren't doing anything to select alternative posts because after checking if the ID was sent. You don't do anything with it. Change your SQL to select id's greater than it if it exists.
$postedId = (int)$_POST['id'];
$sql = "SELECT * FROM posts order by id desc WHERE id > $postedId limit 6";
You want to make sure that the id is escaped to prevent any sort of SQL injection. So as a simple measure, I converted it to an integer (I am assuming on that). Otherwise, you should look into using prepared statements for your queries to prevent SQL injection. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Your SQL query needs to be fixed. Lets say you want to load the next 6 (ordered in descending order by ID). To do this, you should send some kind of variable like offset. Then you can say:
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
Where $end = $offset + 6;
Before using this, though, be sure to check that $offset is numeric to prevent SQL injection. This could be implemented using:
if(i!sset($_POST["id"]) || empty($_POST["id"])){
die("No ID value present.");
}
$offset = (isset($_POST['offset']) ? $_POST['offset'] : 0);
if(!is_numeric($offset)){
die("Abnormal input detected.");
} else {
// Input is numeric
$offset = intval($offset);
}
$end = $offset + 6;
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
/* Your code for actually querying the DB and processing results */
Note: I'm not too familiar with PDO, however, this should be compatible with PDO and safe/secure to use.
Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}