I have a "show more" button to display 5 of last entries into database, with initial display of 1 record, like to change the initial variable to 3 results shown, here's my code:
$latest_entry_qry="SELECT *
FROM cityres
ORDER BY id DESC
LIMIT 0 , 5";
$latest_entry=mysql_query($latest_entry_qry);
?>
<div id="just-head"> <b>Recently Added:</b></div>
<div id="just-added">
<?
$modu = 1;
while($latest_entry_row=mysql_fetch_array($latest_entry))
{
if($modu%5 == 1)
$clsText = "";
else
$clsText = " class='show_more' style='display:none' ";
Here is a guess as your while loop is incomplete. I am assuming at the end there is a -
$modu++;
since you are checking $modu%5 == 1 every time in the while loop. if so, then you could just change it from
if($modu%5 == 1)
to
if($modu <=3)
Also, make note of #Daedalus comment about no longer using mysql_* functions
Related
Okay so here my question i have a blog and i want to show user on first page only 5 posts so i execute this query
mysql_query("select * from posts LIMIT 5");
And then after showing 5 post i made a button named as: Show more posts
when user click on that button another PHP file(loadmoreposts.php) executed in which i execute this query
mysql_query("select * from posts LIMIT 5 OFFSET 5");
but i want to show user 5 post every time it clicks on that button so i make this loop in my PHP script loadmoreposts.php
include('dbConnectClass.php');
$connect = new doConnect();
$beforequery = mysql_query('select * from posts ORDER BY id DESC LIMIT 1;');
if (mysql_num_rows($beforequery) > 0) {
$max_public_id = mysql_fetch_row($beforequery);
$lastid = $max_public_id[0]; //Here it is
}else{
$lastid = "[0]";
}
echo "Last ID $lastid<br />";
$m=5;
for($n=5; $n<=15; $n++):
$afterQuery = mysql_query("select * from posts LIMIT $m OFFSET $m");
$m = $m+5;
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>";
}
echo $result;
endfor;
Let me explain what i did in this script, first i connect to database by a class then i grab last id of my post(last updated post) by running $beforequery and then one more time i execute another query named as $afterquery and then i get my results
but i don't want to show all my posts only in one click i want to show them 5 at a time when user click on that button like first five are already showing but clicking on button will show 5 more then after clicking again it will show the next 5 posts.
this script is then grabbed by this AJAX script:
var loadmoreposts = function () {
$.post('assets/includes/fetchMoreRows.php').done(function( data ) {
$('#displaymoreposts').html(data);
});
}
This loadmoreposts(); fuction is running in onload="loadmoreposts();"body tag
Any Suggestions and help will be appreciated :)
============================
*EDITED**
===========================
I removed the loop and added this but not working
include('dbConnectClass.php');
$connect = new doConnect();
$m = $_POST['offset'];
$afterQuery = mysql_query("select * from posts LIMIT 5 OFFSET $m");
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>" ;
// $result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}
echo $result;
and JS/AJAX script is now this
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}
Your AJAX script needs to send the current value for OFFSET, starting with 0. Everytime you click on your Show more posts link, it increases the value by 5.
So you should change your AJAX script to:
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}
In your PHP script, you can grab the offset value like that:
$m = $_POST['offset'];
Also don't increase LIMIT. Change your query to:
mysql_query("select * from posts LIMIT 5 OFFSET $m");
If you increase LIMIT, the script will return +5 more posts everytime.
Hope that helps.
You can simply send the offset in the AJAX request, and use that offset in your query, here are simple steps:
Load first 5 posts, make the value sent by AJAX "load more" button be 5
When "load more" button is clicked, take the value sent (in our case 5) and insert it in the query (hopefully using prepared statements for security) and retrieve next 5 posts and send back the 5 posts and the new value for "load more" button which is now 10 (can be calculated by adding 5 to the value you got from the AJAX request
repeat, by sending 10 when the "load more" button is clicked, retrieving next 5 posts starting at number/offset 10, returning the 5 posts and the new value for the "load more" button which is 15 (10 + 5)
and so on ...
Try this..
//variable to hold the offset
var offSet = 5; //initial value
//send this in your post request
$.post('url', {aOffset : offset }, function(returnedData) {
// do something here
//update the offset value
offset+=5; });
I am developing on an HTML page a "go to next record" button.
Well, it goes to the next record once and then stops. Nothing happens when clicking on the "Prior Issue" button after the initial click. Since I increment the issue number, the cursor should move to the next record. I am only working on the "Prior Issue" button currently.
HTML syntax:
<a href="index.php?content=main_window&id=1" title="Show More Recent Issue" >< Next (Newer) Issue</a>             <a href="index.php?main_window&id=-1 title ="Show Older Issue" >Prior (Older)) Issue ></a>
The variable "id" is past to:
// Get Cycle Direction "1" stands for newer issue, "0" No Direction set, "-1" stands for older issue
if (!isset($_REQUEST['id']))
{$cycle_direction=0;
} else {
$cycle_direction = trim($_REQUEST['id']);
}
Which then gets past to: (only working on the "case -1" at this time.
switch(trim($cycle_direction))
{
case -1:
// display an older issue
echo "Decrement<br>";
$current_record_number=$current_record_number +1;
echo $current_record_number;
mysqli_data_seek($result, 0);
mysqli_data_seek($result, $current_record_number);
$row=mysqli_fetch_row($result);
printf ("%s \n",$row[0]);
$issuenum=$row[0];
break;
case 0:
// display current issue
//echo "No Selection";
break;
case 1:
// display newer issue
//echo "Increase";
$issuenum=2165;
break;
}
Do it right way. All what you need is url with next/prev record's ids.
$current_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// in case you are using MySQL
$query = "SELECT
prev_id, next_id
FROM
(SELECT
id AS prev_id
FROM
issues
WHERE
id < $current_id
LIMIT 1) a,
(SELECT
id AS next_id
FROM
issues
WHERE
id > $current_id
LIMIT 1) b";
// fetch query data
$prev_id = ...
$next_id = ...
// SHOW CURRENT ISSUE
echo '<a href="index.php?content=main_window&id='.$next_id.'" title="Show More Recent Issue" >< Next (Newer) Issue</a> - <a href="index.php?main_window&id=$prev_id title ="Show Older Issue" >Prior (Older)) Issue ></a>';
In case you get your data from any other db, the logic is the same. Just select previous and next ids, and provide urls using $prev_id and $next_id.
Another solution using MAX/MIN trick.
$query = "SELECT
(SELECT MAX(id) FROM issues WHERE id < t.id) as prev_id,
(SELECT MIN(id) FROM issues WHERE id > t.id) as next_id
FROM issues t WHERE t.id = $current_id";
"Beta" version now working. I stripped the code down to the very bare essentials and added many echo statements to observe how the program responded. The short answer, PHP does not have a memory between each web-page so the values of the variables are "lost". While I was dimly aware of this, it did not become obvious for a while.
The solution was to develop a several $_SESSION variables to hold the array and to monitor the location of the cursor.
<?php
// Start the session
session_start();
include ("establish_array.php");
?>
The code below constitutes "establish_array.php" to establish the array in: "$_SESSION['result']".
<?php
require_once 'php_data/login_data.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the sfmags database server');
$query = "Select IssueIDNUM FROM tblIssueList ORDER by IssueDate DESC, IssueIDNUM ";
$_SESSION['result'] =$conn->query($query);
if (!$_SESSION['result']) die($conn->error);
$_SESSION['rowcount'] = mysqli_num_rows($_SESSION['result']);
?>
The code below is embedded in a case (switch) statement to move the magazine issue to the next older magazine when the pseudo "next" HTML key is pressed. The function "return_row_number();" returns the current row number, +1 is added to the row number and "mysqli_data_seek" is used to move to the next (older) record (issue).
$issuenum = $_SESSION['issuenum'];
$_SESSION['cursor_location'] = return_row_number();
echo "Cursor Location :" . $_SESSION['cursor_location'] . "<br>";
$_SESSION['cursor_location'] = $_SESSION['cursor_location'] + 1;
mysqli_data_seek($result, 0);
mysqli_data_seek($result,$_SESSION['cursor_location']);
$row=mysqli_fetch_row($result);
$issuenum=$row[0];
$_SESSION['issuenum'] = $issuenum;
echo "Issue Number: $issuenum <br>";
Thanks to: misunderstood, Unheiiig, and Alexander Ravikovich for providing useful advice and clues.
Update
This is what I got from your comment:
function return_row_number() {
// Loop through the Array; Get Row Number for the current issue global $result,$issuenum, $rowcount;
$count =0;
mysqli_data_seek($result, 0);
while($row=mysqli_fetch_array($result, MYSQL_ASSOC)) {
++$count;
if($issuenum == $row['IssueIDNUM']) {
return $count -1; break;
}
}
}
Now the mystery value is $issuenum.
And there is a terminology problem. This is not "Looping through an Array" it is querying the database and and looping through the query results.
This is a rather inefficient method of finding the next record. But before correcting that, you need to explain where the value for $issuenum is coming from.
It would also help to know more about the database table especially:
How many issue records?
What is the numbering scheme?
How often does a new issue get added?
end of update
With this line of code you will always get a value of 1
$current_record_number=$current_record_number +1;
because $current_record_number = 0.
You should add the current issue to the href where xx=current record #.
I changed "id" to "cycle"
added content= to Next href.
<a href="index.php?content=main_window&cycle=1&rec=xx"
title="Show More Recent Issue" > < Next (Newer) Issue</a>
           
<a href="index.php?content=main_window&cycle=-1&rec=xx
title ="Show Older Issue" >Prior (Older)) Issue ></a>
Then add this to your PHP:
$current_record_number = intval($_GET['rec']);
And change:
$cycle_direction = trim($_REQUEST['id']);
To:
$cycle_direction= intval($_GET['cycle']);
Instead of trim and isset you should just use intval()
$cycle_direction = intval($_REQUEST['id']);
Also instead of $current_record_number=$current_record_number +1;
You could use: $current_record_number += $cycle_direction
and eliminate the switch.
Unconventional approach
Let's say issues have values from 1 to 10.
$next[-1] = array(0,10,1,2,3,4,5,6,7,8,9,1);
$next[1] = array(0,2,3,4,5,6,7,8,9,10,1);
$next[0] = array(0,1,2,3,4,5,6,7,8,9,10);
$nextIssue = $next[intval($_REQUEST['id'])];
If issues are numbered 2001 to 2010
$nextIssue = 2000 + $next[intval($_REQUEST['id'])];
No matter how many issues you have there is no need to use a database.
Create the $next array as shown above, then save the array.
$fp = fopen('next.ser','w');
fwrite($fp,serialize($next));
fclose($fp);
When you need the $next array in an app use:
$next= unserialize(file_get_contents('next.ser'));
Hi I'm retrieving my data from DB
my data is (pic & name ) when I retrieved them I put them in 4 columns
now I wanna limit the number of rows in each page , I want each page shows three rows only
and if there is more data I want to make it display in next page
my code :
<?php
$items_in_row = 4 ;
$index = 0 ;
?>
<table>
<tr>
<?php
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)){
$index++ ; ?>
<td>
<p>
<img id='g1' src='/<?php echo $row["img"] ;?>' width=130 height=130 onClick='f1()'>
</p>
<p> Name: <?php echo $row['name'] ; ?> </p>
<br>
</td>
<?php if ($index%$items_in_row == 0){ ?>
</tr>
<tr>
<?php }
} ?>
</tr>
</table>
One way to do this is to use the LIMIT() function in SQL, passing in variables that you are storing in the session in PHP. Let's say you want 3 rows of 4 pictures on each page, then you want 12 pictures. So you do something like
select * from pictures LIMIT(0,12)
This returns the first 12 items.
You can do it by just tracking page number. Maybe you have a $page variable in your PHP. If you are on page 2, $page contains 2. Use that to construct a dynamic SQL query with your PHP maybe like this...
$sqlQueryStatement = "select * from pictures LIMIT(". ($page-1)*12 . ", 12)";
What this does is for page 2, it produces the sql statement:
select * from pictures LIMIT(12,12)
See how that works? Now you execute that SQL, and you have the set of results that should be output for page 2.
You can use some further logic to take these basic concepts and run with them...extending them to uses like creating the clickable pagination numbers on the bottom of your results and so forth.
i develop my pagination jobs using the following algorithm:
...1) selecting the results
$page = 1; // what page to show, if you dont know 1 is default.
$maxthingsperpage = 5; // how many things (etc. what you show) per page
$offset = ($page * $maxthingsperpage) - $maxthingsperpage; // db id to start reading
$result = mysql_query("SELECT * FROM things LIMIT ".$offset.",".$maxthingsperpage);
...2) display the things into page
$numrows = mysql_num_rows($result);
$numthingstodisplay = ($numrows > $maxthingsperpage ? $maxthingsperpage : $numrows);
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)) {
... display here without worrying about when to break; num rows are exact
}
you can replace $maxthingsperpage with your $items_in_row
<?php $name=$_POST['name']; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name">
<input type="submit" value="GO" name="submit">
</form>
<?php
include ('db.php');
if(isset($_POST['submit']))
{
mysql_query ("INSERT INTO example (name) VALUES('$name')") or die(mysql_error());
}
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
}
else {
$startrow = (int)$_GET['startrow'];
}
$query = "SELECT * FROM example ORDER BY id DESC LIMIT $startrow, 20";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<li>";
echo $row['name'] ." "." <a href= 'like.php?quote=" . urlencode( $row['name'] ) . "'>Click Here</a>";
echo "</li>";
}
echo 'Next';
?>
I want to make my page links hidden , how can i make then hidden so that a user cant edit it.
2nd question,
currently i am showing total 10 records on each page and then a next page button , but the next button is keep showing even when there is no more records...! how to remove a next page button when records ended. ??
line number 28 is the link to pages which can be easyily editable by any user, i wnat to make them secure (using ID)
and line 35 is n'next' page link , this link should not be appear when number of records ended
I can't think of a reason why you really should hide the page numbers from the user in the link. Keeping them in the query string as $_GET variables is probably the most common practice i know of in this specific case of paging.
I would do validation on the numebrs being recieved in the $_GET variables, since this could often lead to SQL Injection and other problems... Make sure it's a number, possibly divisible by 10 (if that's how you like the site to be), perhaps not bigger than a certain defined number, etc...
If you REALLY still don't agree, and you want to hide it, then you could always do that by saving cookie on the user's computer (this is still exposed to user in some way) or save the page number in the session (although this seems like a big waste of server resources to me!).
About your second question - There are so many possibilities to this...
Here's one way :
Create an sql query that queries how many rows are there to your table.
Let's say the number is 55. You put that into a hidden value.
If you're displaying 10 items on a page then you know the last page is number 6 (showing items 50-55, if you start counting at page number 1).
Simple php check when page loads: if ($_GET['page'] == 5) then you don't display the next button.
something like this (skipping out validation checks and the sql query) :
<input type="hidden" value="<?php echo $itemCount;?>">
<?php
if ($_GET['page'] < ($itemCount \ 10))
{
echo "<a href=\"items.php?page=".($_GET['page']+1)."\">";
}
?>
Using this, I would add a check to make sure the user doesn't enter a number bigger than this number as well, and if they do, just redirect them to the last number they can.
I found this script on about.com which I'm trying to learn from on how to create a rating system but the script for some reason wont count a vote when the link is clicked and just reloads the page.
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Here is the full script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie])) {
echo "Sorry You have already ranked that site <p>";
} else {
//Otherwise, we set a cooking telling us they have now voted
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
echo "Your vote has been cast <p>";
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data )) {
//This outputs the sites name
echo "Name: " .$ratings['name']."<br>";
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
} else {
$current = 0;
}
echo "Current Rating: " . round($current, 1) . "<br>";
//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
echo "Rank Me: ";
echo "Vote 1 | ";
echo "Vote 2 | ";
echo "Vote 3 | ";
echo "Vote 4 | ";
echo "Vote 5<p>";
}
?>
$mode is never set? While it may have worked if register globals was on, it is not on by default any more (and is removed in later versions of PHP)
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
Maybe you mean
if ( $_GET['mode']=="vote") {
The same goes for $id and $voted, which are also never set.
EDIT
I also would like to add, that if I went and changed id to 1';DROP TABLE vote; You would have a whole lot of data lost. Look at SQL Injection
EDIT
If the row in the table doesn't exist, you will need to INSERT it before you can UPDATE it.
I can also see $cookie is never set, looking at the code it should be 'Mysite' . $id. I added quotes for the string, though PHP will treat any unquoted text as string but avoid misunderstanding and errors later, its always a good idea.
Also this script assumes PHP option register_globals is on, you need to make that register_globals = ON in your php.ini