I have an image gallery, at the moment I limit the results to 10.
What I'm trying to do, through jQuery, is on click of the 'Load more Results' button, Load the next 10 rows(images) in the database.
at the moment I use a class query.php to make my query call, then in my index.php display the data in a foreach loop.
I was thinking perhaps using the query string to change the limit to rows 10-20 on click but finding difficulty in this.
Any help will be appreciated.
class query.php
public function Query($db_table, $limit) {
$this->db_query = mysql_query("SELECT * FROM $db_table ORDER BY time DESC limit $limit");
while($row = mysql_fetch_array($this->db_query)) {
$rows[] = $row;
}
return $rows;
}
index.php
$lim = $_GET['limit'];
$Results = $Database->Query('info', $lim);
if(is_array($Results)) {?>
foreach ($Results as $Result) {
//echo results
jquery
$("#my_container").load("../lib/class.database.php?limit=10,20" );
Kind regards, Adam
2 Answers 2
It's very simple:
1.) You make an AJAX call to your PHP script
$.ajax(
{
url: "get-ajax-images.php",
data: "mode=ajax&start=10&end=20",
success: function() { /* ... */ },
error: function() { /* ... */ }
});
2.) PHP: Load the data from the database based upon start and end
<?php
header("Content-type: application/json");
// Please use intval() to avoid SQL injections!!
$start = isset($_GET['start']) ? intval($_GET['start']) : exit('{"error": true}');
$end = isset($_GET['end']) ? intval($_GET['end']) : exit('{"error": true}');
/* valid start and end? */
if ( $start < 0 || $end < 0 )
exit('{"error": true}');
if ( ($end - $start) <= 0 ||
($end - $start) > 15 )
exit('{"error": true}');
/* All right! */
$sql = "SELECT id, imagepath FROM images LIMIT $start, $end";
$result = mysql_query($sql) or exit('{"error": true}');
$data = array();
while ( $row = mysql_fetch_assoc($result) )
{
$data[] = $row;
}
echo json_encode($data);
5 Comments
$_GET['start'] and $_GET['end'] to integers!intval() there (which was not emphasized, even though the OP committed this mistake in his code).Here's the jquery part for you question
http://jsfiddle.net/manuel/e5kXc/
it holds the total amount of loaded results and you could use the var's limit and total for quering the correct results
intval()to avoid SQL injections:$lim = intval($_GET['limit']). And you don't limit the number of images, so someone could overload your database! See my answer ;)