How do I show next result in MySQL on "onclick" in JavaScript? - php

I want to show a certain amount of results (say, 5) and make a:
<a href="" onclick="<?php ShowNextResult(); ?>">
And use onlick to show the next 5 results.

EDIT ::
HTML
<div id="results">
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
</div>
<a href="#" id="showMore" />Show more</a>
JAVASCRIPT
Use Jquery as below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
});
</script>
PHP
you should make a new php page (getNext.php ) that will get query results
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons LIMIT {$_POST['count']},5");
while($row = mysql_fetch_array($result))
{
echo "<div class='result'>".$row['FirstName'] . " " . $row['LastName']."</div>";
}
mysql_close($con);
?>
HELP
you can use SQL something like
SELECT x,xx,xxx FROM XxXxXs Limit $_POST['count'],5

Since you specifically mention JavaScript I assume you don't want to reload the page or anything like that. Your onClick will have to trigger an AJAX call to a php page on your server that will handle the request and give you back the next five records (or the last 5, or random ones, etc...).
JQuery is really popular for doing this and have built in functionality to make this process easier.
http://api.jquery.com/jQuery.ajax/
Here are some tutorials: http://docs.jquery.com/Tutorials
Your best bet is to write this functionality w/o using JavaScript. Make the page accept arguments to show specific records. Once you have that code done, then put the AJAX on top of it, but that way you'll have the older stuff to fall back on if you need to for compatibility or things don't work the way you need them to.
These are pretty general answers, do you need specific help making the query to only show the next 5 records? Or the specific PHP code to tie it together? Or just the JS to do the AJAX stuff? Could you be more descriptive if you need more info.

change
data: "count=$number",
to
data: "count=" + $number,
because then it isn't work!

Here's my solution that showing quiz questions partially with next button means on each click at Next Button 5 more question will display.
<?php
$strSQL="SELECT * FROM `quizes` WHERE Q1 IS NOT NULL ORDER BY RAND()";
$result=mysql_query($strSQL);
while($row=mysql_fetch_array($result)){
$c=0;
$q[]= $row['Q1']; // This is database record that has all question stored as array
?>
<?php
for($inc=0; $inc < $ret; $inc++){ ?>
<table>
<tr id="<?php echo "i".$inc ?>">
<td id="qs"> <?php print_r($q[$inc]); ?></td>
</tr></table>
<!-- here in i am display all question with loop in this variable $q[$inc] -->
<?php } ?>
// Now we are going to display partial
instead of all so data will display partially with next button
Next/Show More
//this is anchor/button on which more questions will load and display when clicked
//CSS question are placing in tr (table row) so first hide all question
<style>
tr{
display:none
}
</style>
//jquery now we will show partial question 5-questions at each click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id=i0],[id=i1],[id=i2],[id=i3],[id=i4],[id=i5]").show();
//Display first 5-question on page load other question will
//show when use will click on next button
var i=0;
$("#more").click(function(){ // Next button click function
//questions tr id we set in above code is looping like this i1,i2,i3,i4,i5,i6...
i=i+5; //at each click increment of 5 question
var e=i+5;
//start after the last displayed question like if previous result was 1-5 question then next result should be 5-10 questions...
for(var c=i; c < e; c++ ){
$("[id=i"+c+"]").show();
}
});
});
</script>

Related

How to save and retrieve contenteditable data

I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.
This is how I would like it to work:
Admin hits a button 'edit'
div becomes editable.
When the admin is ready editing, he hits a button 'save'
The data is saved to a file or database (don't really know what would be the best option).
The edited content shows up when the page is opened.
This is all I have for now:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.
Thanks for your help,
Samuël
EDIT:
#gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.
Here's my code:
over_ons.php:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
<input type="button" value="Send Data" id="mybutt">
<script type="text/javascript">
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'sent_data.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
</script>
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
$tekst=$_POST['myTxt'];
$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
mysql_query($query);
?>
Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?
SOLUTION:
It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.
over_ons.php:
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
<?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show content
echo $inhoud;
?>
</div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editable").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.
Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.
Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:
jsFiddle Demo
$('.editable').prop('disabled',true);
$('.editbutt').click(function(){
var num = $(this).attr('id').split('-')[1];
$('#edit-'+num).prop('disabled',false).focus();
});
$('.editable').blur(function(){
var myTxt = $(this).val();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
PHP file: some_php_file.php
<?php
$myVar = $_POST['varname'];
$secondVar = $_POST['anothervar'];
//Now, do what you want with the data in the vars
Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.
Here are some basic examples to bring you up to speed on ajax:
AJAX request callback using jQuery
There is no short path to learning jQuery or AJAX. Read the examples and experiment.
You can find some excellent, free jQuery tutorials here:
http://thenewboston.com
http://phpacademy.org
UPDATE EDIT:
To respond to your comment inquiry:
To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.
So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:
How to send DIV content after a button clicked:
HTML:
<div class='big_wrapper' contenteditable>
PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />
jQuery:
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
You could save the whole
page clientside with this:
<script>
function saveAs(filename, allHtml) {
allHtml = document.documentElement.outerHTML;
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
</script>
hth

Endless Scroll with Jquery, PHP, and Ajax

So I'm trying to impliment an endless scroll pulling from a table in my mysql database and I have it so that when the bottom of the page is reached it will call for a new number of reviews to be pulled to the newsfeed but for some reason when it gets to the bottom but just shows the loading gif and nothing new loads. Any help where I am messing up would be awesome. Thanks guys
Here is my jquery/ajax:
<script>
//Script to continue the home newsfeed after 10 posts
$(window).scroll(function() {
if($(window).scrollTop() === $(document).height() - $(window).height()) {
$('div#load_more_posts').show();
$.ajax( {
url: "load_more_posts.php?lastPost=" + $(".display_newsfeed:last").attr("id"),
success: function(html) {
if(html) {
$("#outputDiv").append(html);
$('div#load_more_posts').hide();
} else {
$('div#load_more_posts').replaceWith("<center>Finished loading all Posts!</center>")
}
}
});
}
});
</script>
Here is the part of the code where the newsfeed is called:
<div class="outputDiv">
<?php echo "$outputList"; ?><!-- Div for this output has been declared above in PHP before echoing -->
</div> <!-- END outputDiv -->
<div id='load_more_posts' style="display:none">
<center>
<img src="../../images/loading.gif" alt="Loading" />
</center>
</div>
And lastly, Here is the Newsfeed display for each review (display_newsfeed.php):
$review_query = mysql_query("SELECT * FROM `reviews` ORDER BY `review_date` DESC LIMIT 0,10");
while($review_row = mysql_fetch_assoc($review_query)){
$review_title = $review_row['review_title'];
$user_id = $review_row['user_id'];
$user_firstname = $review_row['user_firstname'];
$user_lastname = $review_row['user_lastname'];
$review_id = $review_row['review_id'];
$review_body = $review_row['review_body'];
$review_referral = $review_row['review_referral'];
$outputList .= '
<div class="display_newsfeed" id="'.$review_id.' display_newsfeed">
This code is each review
</div>
';
You're missing a closing bracket in your while loop in display_newsfeed.php. You're also referencing a div with an ID of 'outputDiv' in your javascript, but that element doesn't exist (you're assigning it a CLASS of 'outputDiv' in the HTML). Not sure if these were just typos pasting the code here, but either of those could definitely cause the issue.
If none of those is the issue, the best next step would be identifying where the problem is. If your browser has a developer console (or firebug), double check that the AJAX request is going out and see if it's returning the expected HTML. If it is, the problem is definitely with the client-side code (specifically something in the success callback, unless the request isn't going out at all). If not, the problem is definitely with the script on the server.

ajax and php updating mysql

i am having problem updating the database.
Basically what i am trying to do is everytime a download link is clicked the download count in the database goes up.
Can someone point me in the right direction as i have been trying to get this right for hours :(
Here is the html.
<div class="button_border_dark"> <a id="linkcounter" href="http://www.derby-web-design-agency.co.uk/freeby-download/<?php echo $freebies_download ; ?>" target="_blank" title="Download">Click To Download File</a></div>
Here is the jquery
<script>
$('#linkcounter').bind('click',function(){
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
});
</script>
Here is the downloadcount.php which i am trying to post data too, so it updates the content.
<?php
require_once("applications/constants/connection.php");
require_once("applications/controllers/basic.php");
if(isset($_REQUEST["linkid"])){
$linkid = sanitise($_POST["linkid"]);
$updatedownload = mysql_query("UPDATE freebies SET download_count=`download_count` +1 WHERE id ='".$linkid."'") OR die(mysql_error());
}
You don't say what is the problem!
Is not incrementing? is incrementing too much? is one process blocking the other? the problem is that people can cheat and make so a file has ben downloaded a million times?
Anyway, I think you code can be simpler.
$('#linkcounter').click(function(){
$("#invisibleiframe").attr("src",$(this).attr("src");
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
return false;
});
this need to create a invisible iframe, that will be the one downloaded the file. after starting this download, the ajax request is made. a single event do the two things. made this way the stuff still works if js is disabled.
I think should be
$updatedownload = mysql_query("UPDATE freebies SET download_count= download_count +1 WHERE id ='".$linkid."'") OR die(mysql_error());
Note the single quote:
SET download_count = download_count +1
Well first off I would not mix the jQuery and PHP personally, this may be the source of your problem, I would try something like this
<div class="button_border_dark" theLinkId="<?php echo $id ; ?>">
<a id="linkcounter" href="http://yourURL/" target="_blank" title="Download">
Click To Download File
</a>
</div>
With the jQuery like this
<script>
$('#linkcounter').bind('click',function(){
var theLinkId = $(this).parent().attr('theLinkId');
$.post("downloadcount.php",{ linkid : theLinkId});
});
</script>
It is possible that your event is not actually being bound to the anchor, because you are running .bind() before the anchor exists. Try this:
<script>
$(document).ready(function(){
$('#linkcounter').bind('click',function(){
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
});
})
</script>
how many anchors you have with id = 'linkcounter' ?
If you have more than one, i recommend you to change 'id' for 'class'
Greatings.
EDIT:
Try something like this:
Link
<script type="text/javascript">
function goToLink(o, id) {
$.post("downloadcounter.php",
{linkid : id},
function () {
window.open($(this).attr("href"));
}
);
return false;
}
</script>

getting query string php - jquery - #?id=

I am really stuck and was wondering if someone could lend a hand please,
i know how to get a query string, thats not a problem,
however,
I have links that use jquery to fade out the content and load the new content via links,
usage example below - class="link2" is a reference for the jquery to do what it does lol
click here
in the href i have to have the # first to stop the page from loading if you get what i mean,
now when i try and get the query string id=2 it says none as there is a # first, there is probably a simple fix for this but i must just be missing it,
i have searched and searched but still cant find the answer
----------------------edit------------------------------
this is what i am trying to do,
enter page,
sql query runs to display all the reports
click a report and the jquery hides "contmain" and shows "contreports" now a new sql query runs to display the report based on the "id"
now usually i can just get this information from the url and clean it up, hovever as i have jquery running i need to have the "#" for the href so the page does not reload and the jquery can run, but now this is stopping me from being able to retrieve the url query,
Interstellar_Coder
he seems to have the right idea, passing it in the background
Although i don't fully understand what you're doing, i'm guessing it would be better to store your querystring as a data attribute.
click here
Then in your jQuery function.
$('.link2').click(function(e){
var queryString = $(this).data('id');
e.preventDefault(); // prevent the default action
});
because of the code i thought it best to post here
i think i am getting close,
#Interstellar_Coder - this is what i have so far but it only ever retrieves the first id,
$query1 = mysql_query("SELECT * FROM `".TBL_CATCH_REPORTS."` order by id DESC");
$query2 = mysql_num_rows($query1);
if(mysql_num_rows($query1) != 0) {?>
<table width="880" style="margin:0 auto">
<?PHP while ($output = mysql_fetch_assoc($query1)) { ?>
<tr class="row">
<td width="190px"><input type="button" class="c_report"value="<?PHP echo $output['id']; ?>" />
View Report <img src="images/icons/arrow_right.png" width="16" height="16" /></a></td>
<td width="210px">Submited by <?PHP echo $output['submitby']; ?></td>
<td width="160px"><?PHP echo $output['date']; ?></td>
<td><?PHP echo $output['title']; ?></td>
</tr>
<?PHP } ?>
</table>
<?PHP }else{ echo '.Sorry there are no catch reports yet'; }?>
<div id="contreport"> content here </div>
<script type="text/javascript">
$(document).ready(function(){
$(".c_report").click(function () {
$("#contreport").html('Getting Catch Report......');
$.ajax({
type: "POST",
data: "data=" + $(".c_report").val(),
url: "reportdata.php",
success: function(msg){
$("#contreport").html(msg)
}
});
});
});
</script>
my other page "reportdata.php just gets the value and is then used in a sql statement
$getreport = '';
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$getreport = trim($_POST['data']);
}
i am assuming i need some kind of loop going on in the jquery but i am just lost, been stuck on this all day today again lol
this is all i need
id 1 - link
id 2 - link
id 3 - link
id 4 - link
id 5 - link
click on any and the id will be sent to reportdata.php where the id will be used in a sql statement, then the data returned and displayed,
its truly sending me mad lol

pagination using javascript in php and mysql

I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>

Categories