Incorporating next/ previous in my 'foreach statement - php

I want to have a previous|next link on my page to change pictures.
I use a function to get relevent elements. However, I do not know what additional code is require in my function and where to place it. Also what should be in the html section.
I have looked at many pages on next/previous from 'foreach' but I cannot seem to relate to them.
Code:
function image_data($image_album_id) {
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
$query = mysql_query("SELECT $fields FROM `album_images`
WHERE `image_album_id`=$image_album_id AND `member_id`= '1'");
$ query_result = mysql_fetch_assoc($query);
foreach ($args as $field) {
$args[$field] = $query_result[$field];
}
return $args;
}
Html Page:
Last|
Next
</div>
<?php
$image_album_id =$_GET['image_album_id'];
$image_data = image_data($image_album_id, 'album_id', 'albumname', 'ext', 'timestamp');
echo '';
?>
<td class="smallfont albumthumb2" align="center" valign="middle" >
<img alt="" class="album_cover" src="<?php echo 'images/albums/thumbs/'. $image_data['album_id']. '/'. $image_album_id. '.' .$image_data['ext'];?> " height="175px" width="175px">
</td>
Many thanks. I hope I make sense.
Thanks for the speedy response.
Since there is a lot to look at and digest I thought I would just see if it works.
Alas no.
There is a parse error: syntax error, unexpected
'<' on line
$prev_link = Previous;
The only thing I notice within that section was an extra curly bracket after 'title="$prev_name"}'
I see there is the same for the 'title="$next_name"}'
WIth reference to your specific questions.
I get to the album_viewT page when I click on a link in a previous page. This contains tiny thumbnails. The link being localhost/Testing/album_view.php?artist_id=4&image_album_id=4 as an example.
Not sure if I fully understand "order of date is by image_album_data
Yes there are almost 3,000 rows in the database.
I should also mention that album_id has been replaced by artist_id.
Should the href be changed to "album_view.php/id/...

Your question lacks some data i.e. what is the page you are visiting that produces this code (the URL that is) and how is your data sorted. For instance I can see that you are providing potentially more information using the album_viewT.php? script but that is not necessarily the one that displays the HTML that you have produced.
So after all this I will make some assumptions and hopefully that will give you the right guidance to get to the solution.
I am assuming that your visiting page is http://mysite.com/albums/id/25
I am also assuming that the order of the data is by image_album_id.
Finally I am assuming that you have data in your db and I don't need to check whether there are returned data in the template for the current image. You will need to sort that out yourself.
You will need to get the data first from the database:
function image_data($image_album_id)
{
$results = array(
'previous' => FALSE,
'current' => FALSE,
'next' => FALSE,
);
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
// Current record
$results['current'] = get_data(
$fields,
"AND image_album_id = {$image_album_id}"
);
// Previous - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['previous'] = get_data(
$fields,
"AND image_album_id < {$image_album_id} " .
"LIMIT 1"
);
}
// Next - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['next'] = get_data(
$fields,
"AND image_album_id > {$image_album_id} " .
"LIMIT 1"
);
}
// If all went well the $results array will contain the data
// for the 3 records. If we are at the beginning or the end,
// the previous and/or next will be FALSE
return $results;
}
function get_data($fields, $where = '')
{
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE member_id = 1 %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
}
For your HTML page:
<?php
$image_album_id = $_GET['image_album_id'];
$image_data = image_data(
$image_album_id,
'album_id', 'albumname', 'ext', 'timestamp'
);
$prev_link = '';
$next_link = '';
if ($image_data['previous'])
{
$prev_id = $image_data['previous']['album_id'];
$prev_name = $image_data['previous']['albumname'];
$prev_link = <a href="/albums/id/{$prev_id}" title="$prev_name"}>Previous</a>";
}
if ($image_data['next'])
{
$next_id = $image_data['next']['album_id'];
$next_name = $image_data['next']['albumname'];
$next_link = <a href="/albums/id/{$next_id}" title="$next_name"}>Next</a>";
}
$curr_id = $image_data['current']['album_id'];
$curr_ext = $image_data['current']['ext'];
?>
<?php echo $prev_link; ?>|<?php echo $next_link; ?>
</div>
<td class="smallfont albumthumb2" align="center" valign="middle">
<a href="album_viewT.php?images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}; ?>
<img alt="" class="album_cover"
src="images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}"; ?>
height="175px"
width="175px" />
</a>
</td>
Note: I have split the line for the img and a tags in the HTML file for clarity.

Related

Display pho echo list in Descending order

Am displaying list haviing
Date
News Heading
Short Descrption
The list is spread to around 100 pages, having 20 news in each page
Issue is: This is working absolute fine in php 7.3, 7.4 in joomla 3.10 where on clicking url - list is shown spread over multiple pages having sort by date wise as first criteria, latest date of publishing is coming
But when same used on php 8.0.x - its showing incorrectly, where on clicking URL - last page of list having page number 100 is shown first. Now when i add on limitstart=0 in url then its showing correctly as the first page.
Now when i change from descending to ascending - its bringing the content on last page and its opening, but page number is 100 again
Seems like URL when opened is directly taking to last page of news item as published (although no limitstart is mentioned in it), which is incorrect as ideally should open in descending order and open the page having latest one
Below is code of views/list/tmpl/default.php
if(count($this->items) >0){
//$i=1;
foreach($this->items as $newslist)
{
$date = JFactory::getDate($newslist->n_date);
$list .='<h3><strong>'.$newslist->v_heading.'</strong></h3>
<p>'. $date->format('F j, Y').'</p>
<p>'.substr($newslist->v_short_description,0,100).'</p>
<p><i>Know More on:- </i><b><i>'.$newslist->v_heading.'</i></b></p><hr/><br>';
//$i=$i+1;
}
}else{
JError::raiseError(404, "Message");
}
<?php echo $list?>
and for models/list.php this is the function
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__news` AS a');
if (!JFactory::getUser()->authorise('core.edit', 'com_news'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.n_heading LIKE ' . $search . ' )');
}
}
/*
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
*/ //Order by date
$query->order ('a.n_date DESC');
$query->order ('a.id DESC');
return $query;
}
This is the code for views/list/view.html.php
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->params = $app->getParams('com_news');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
}
$this->_prepareDocument();
parent::display($tpl);
}
Unsure how to achieve in and why its not working in php 8.0 where url should open the 1st page and not last page

Hide individual sections of a RSFormPro form when submission limit has been reached

I use RsForm Pro on Joomla CMS, and there I have created a form. In my form, I have 5 sections with a checkbox. I want to display individual sections up to a certain limit (let's say a max of 20 users), after the submission limit has been reached the form section needs to be disabled.
I found a limit for submit form, but if 20 users submit only one section in the form (not for checkbox), another 4 can't be available for other users. In other words, I don't want to disable all sections unless all sections have reached there limit.
This is code for limit submit form:
// Define the maximum number of submissions. For this example we'll use 25.
$max = 25;
// Get a database connection.
$db = JFactory::getDbo();
// Setup the query. This query counts the number of submissions for the current form.
// $formId contains the ID of the current form.
$db->setQuery("SELECT COUNT(`SubmissionId`) FROM #__rsform_submissions WHERE `FormId`='".(int) $formId."'");
$submissions = $db->loadResult();
if ($submissions >= $max) {
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!.';
}
EDIT SOLVED:
$limit25 = 25;
$limit21 = 21;
$limit20 = 20;
$db = JFactory::getDbo();
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 11th'");
$first_submission_value = $db->loadResult();
if ($first_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-11th { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 13'");
$secont_submission_value = $db->loadResult();
if ($second_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-13 { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 18'");
$third_submission_value = $db->loadResult();
if ($third_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-18 { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA'");
$fourth_submission_value = $db->loadResult();
if ($fourth_submission_value >= $limit20) {
echo '<style>.rsform-block-evening-qa { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA_2'");
$fifth_submission_value = $db->loadResult();
if ($fifth_submission_value >= $limit21) {
echo '<style>.rsform-block-evening-qa-2 { display:none;}</style>';
}
if(
$first_submission_value >= $limit25
&& $secont_submission_value >= $limit25
&& $third_submission_value >= $limit25
&& $fourth_submission_value >= $limit20
&& $fifth_submission_value >= $limit21
) {
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
}
I see that you have edited your question to reveal your solution. Rather than to ask you to post your solution as an answer (which you should have done), I'll do you one better -- I've taken the time to refactor your code, implement Joomla's query building methods, make it more efficient, cleaner, more direct, and easier to manage.
Most importantly, because all of the database interactions can be performed with a single query, they should be.
Because your field names seamlessly relate to your classnames, a "lookup array" or "mapping array" will allow my snippet to reliably deliver your desired results dynamically. You will never need to adjust more than $formId and $field_maxes.
Code: (tested locally with my own rsform pro table)
$formId = 3; // or whatever the correct formId value is
$field_maxes = [
'Bus_Blockchain_March 11th' => 25,
'Bus_Blockchain_March 13' => 25,
'Bus_Blockchain_March 18' => 25,
'evening_QA' => 20,
'evening_QA_2' => 21
];
$classes_to_hide = []; // initiate as empty array
$formLayout = ''; // initiate as empty string
$db = JFactory::getDbo();
$quoted_fields = implode(',', $db->q(array_keys($field_maxes))); // create quoted comma-separated values
$query = $db->getQuery(true)
->select("FieldName, COUNT(1) AS " . $db->qn("Count"))
->from("#__rsform_submission_values")
->where([
"FormId = " . (int) $formId,
"FieldName IN ($quoted_fields)"
])
->group("FieldName")
->order("FIELD ($quoted_fields)");
// if you wish to see the rendered query, uncomment the next line (do not show to public)
// JFactory::getApplication()->enqueueMessage("<div>" . $query->dump() . "</div>", "notice");
try // listen for syntax errors
{
$db->setQuery($query);
if (!$results = $db->loadAssocList()) // declare and check for empty result set
{
echo "No Results in Form";
}
else
{
foreach ($results as $row) // iterate rows
{
if ($row['Count'] >= $field_maxes[$row['FieldName']]) { // if fieldname has reached limit
$classes_to_hide[] = ".rsform-" . str_replace(['_', ' '], '-', $row['FieldName']);
}
}
if ($tally = sizeof($classes_to_hide)) // declare and check if not empty
{
echo "<style>" , implode(", ", $classes_to_hide) , " {display:none;}</style>"; // apply css styling to one or more designated classes
if ($tally == sizeof($field_maxes)) // if all fieldnames are full
{
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
}
}
}
}
catch (Exception $e)
{
JFactory::getApplication()->enqueueMessage("Query Syntax Error", "error");
// if you have a syntax error and wish to see the message, uncomment the next line (do not show to public)
//JFactory::getApplication()->enqueueMessage($e->getMessage(), "error");
}

stopping duplicate urls in a form submission

I have a community site, where people can put up pages, and the url generates from their name. e.g. My Business, becomes my-business. I want to create a way, that if there is another My Business, it will check and make the url my-business-2, my-business-3, etc.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$slugs = array();
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
if(in_array($url, $slugs)) {
$max = 1;
while(in_array(($url . '-' . ++$max ), $slugs)) $url .= '-' . $max;
}
}
return $url;
}
This is my function, but this still wont work, as if there is a business called My Bus, it will make it my-bus-2, when it would have been unique at my-bus. I have experimented with other functions too, but this one is the closest I got. Can anyone tell me one that works perfectly?
So form my understanding, you are trying to avoid inserting/generating duplicate URL. Output will be something like this -
www.example.com/my-business
www.example.com/my-business-1
www.example.com/my-business-2
www.example.com/my-business-3
...
Try using this function -
function check_url($base_url, $new_url='', $num=0) {
if($new_url == '') {
$new_url = $base_url;
}
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url = '$new_url'");
if(mysqli_num_rows($qry) > 0) {
while($row = mysqli_fetch_array($qry)) {
$num++;
check_url($base_url, $base_url . '-' . $num, $num);
}
}
return $url;
}
Basically, this function will check the database until it finds a valid URL. Each time it will increment the number and recursively call the same function to generate new/valid URL.
Simple and basic!
#SpritsDracula has working code, but his function will query your database each time it executes. That being said, the recursion is a nice concept. Here is a piece of code that will save your the multiple database calls.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$baseUrl = $url;
$slugs = [];
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
$max = 1;
while(in_array($url, $slugs)) {
$url = $baseUrl . "-" . $max++;
}
}
return $url;
}

Programming CRUD functions in PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm writing some CRUD functions in PHP (not object oriented), and I ran into a little trouble. The function works just fine as is. Please review and read ahead for the actual issue I'm having. Here's the function:
<?php
function db_s(
$table,
$condition = array(),
$limit = '',
$order = array(),
$group = array(),
$return_query_string = false
) {
$sql = '
SELECT
*
FROM
`'. $table .'`
';
if (is_array($condition)) {
if (count($condition) > 1) {
$sql .= '
WHERE
';
$sql .= implode(' AND ', $condition);
}
elseif (count($condition > 0)) { $sql .= ' WHERE '. $condition[0] .' '; }
}
elseif ($condition != '' && is_string($condition)) { $sql .= ' WHERE '. $condition .' '; }
if (!empty($group)) {
$sql .= '
GROUP BY
';
$sql .= implode(', ', $group);
}
if (!empty($order)) {
$sql .= '
ORDER BY
';
$sql .= implode(', ', $order);
}
if ($limit != '') {
$sql .= '
LIMIT
'. $limit .'
';
}
//print '<pre>'. $sql .'</pre>';
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if ($return_query_string) { return $sql; }
else { return $query; }
} // end db_s() function
?>
And here are some examples of how you would use it:
<?php
$results = db_s('users', 'active = 1');
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10);
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC');
while($row = mysql_fetch_assoc($results)) {
// do cool stuff here
}
?>
<?php
$results = db_s('posts', 'unread = 1', '', 'date ASC', 'user_id', true);
print '<pre>'; print_r($results); print '</pre>';
?>
All of this works just fine (pending any syntax errors above but the function works fine). The problem is in the way I want to use the function. As you can see above, I must first establish the $results variable. Then I have to put the whole thing into a while loop with $row = mysql_fetch_assoc($results). That seems like too much work for me. In order to really make this function useful to me, I'd really like to rewrite it so I can use it like this:
<?php
while ($row = db_s('messages', array('user_id = 1512', 'date < "2014-05-01"'), 10, 'date DESC')) {
// do cool stuff here
}
?>
Or like this:
<?php
while ($row = db_s('users', 'active = 1')) {
// do cool stuff here
}
?>
In order to do that, I've tried rewriting the end of the function (the part that actually returns the query), but I can't seem to get it to work correctly. I've tried something like this
}
//print '<pre>'. $sql .'</pre>';
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if ($return_query_string) { return $sql; }
else { return mysql_fetch_array($query); } //<--- this line is modified
} // end db_s() function
?>
But it just doesn't work like that. Unfortunately the results are... spotty... when used like this. Often it returns more results than it should, and it only spits out the first result several times... I did rewrite the while() loop so it would use the function db_s() correctly. Can anyone provided me any insight as to why it wouldn't work like this? Or perhaps, how to return the results so I can use the function as I intend to? Any help is greatly appreciated. Thanks in advance!
You need to get on PDO or MySQLI now. The solution would be similar or you could use the *_fetch_all() for those libraries.
For the function return:
$query = mysql_query($sql) OR die(mysql_error() .'<p><pre>'. $sql .'</pre></p>');
if($return_query_string) {
return $sql;
} else {
while($result[] = mysql_fetch_array($query)) {}
return $result;
}
Then use it like this:
foreach(db_s('users', 'active = 1') as $row) {
//do cool stuff here
}
I'm not endorsing the function or the code concept, just answering the question.

php image gallery pagination

I am trying to add a simple pagination to an image gallery but I reach a point where I don't get any error messages and it still is not working. I don't know where to look for a mistake.
My code is;
<?php
include 'core/init.php';
ini_set('display_errors', 'On'); // aan of uit
error_reporting(E_ALL);
?>
<body>
<div id="wrap">
<div id="header">
<h1>Rob Cnossen</h1>
</div>
<div id="titel">
<?php
if (isset($_GET['album_id'])) {
$album_id = $_GET['album_id'];
$album_data = $albums->album_data($album_id, 'name', 'description');
echo '<h2>', $album_data['name'], '</h2>';
$albums = $albums->get_albums();
$images = $images->get_images($album_id);
}
?>
</div>
<div id="sidebarleft">
<?php
if (empty($images)) {
echo 'Er zijn geen foto\'s in dit album';
} else {
foreach ($albums as $album) {
foreach ($images as $image) {
?><div id="fotoos"><?php
if ($image["album"] === $album["id"])
echo'<img src="uploads/thumbs/', $image["album"], '/', $image["img_name"],'" title="" /><div id="kruisje">_|</div>';
?></div><?php
}
}
}
?>
<div id="pagination">
<?php
$count_query = $db->prepare('SELECT * FROM images where album_id= ?');
$count_query->bindValue(1, $album_id);
try{
$count_query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
$count = $count_query->fetchColumn();
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#,",$_GET['page']);
}else{
$page = 1;
}
$limit = 2;
$lastPage = ceil($count/$limit);
if($page<1){
$page = 1;
}elseif($page>$lastPage){
$page = $lastPage;
}
$offset = ($page-1)*$limit;
$query = $db->prepare('SELECT image_id FROM images WHERE album_id= ? ORDER BY image_id DESC
LIMIT ?,?');
$query->bindValue(1, $album_id);
$query->bindParam(2, $offset, PDO::PARAM_INT);
$query->bindParam(3, $limit, PDO::PARAM_INT);
try{
$query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
if($lastPage !=1){
if($page != $lastPage){
$next = $page + 1;
$pagination='Volgende';
}
if($page != $lastPage){
$prev = $page - 1;
$pagination.='Vorige';
}
}
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['image_id'];//This echoes out two image id's, at the moment that is number 75 and 73
}
echo $pagination;
?>
</div>
</div>
</div>
</body>
The get_image function is;
public function get_images($album_id) {
$images = array();
$count_query = $this->db->prepare("SELECT `image_id`, `image_name`, `album_id`, `timestamp`, `ext` FROM `images` WHERE `album_id`=? ORDER BY `timestamp` DESC");
$count_query->bindValue(1, $album_id);
try{
$count_query->execute();
while ($images_row = $count_query->fetch(PDO::FETCH_ASSOC)) {
$images[] = array(
'id' => $images_row['image_id'],
'img_name' => $images_row['image_name'],
'album' => $images_row['album_id'],
'timestamp' => $images_row['timestamp'],
'ext' => $images_row['ext']
);
}
return $images;
}catch(PDOException $e){
die($e->getMessage());
}
}
I think there is something wrong in the $pagination variable but I don't know what.I got seven images in this album and the $limit is standing on 2, still all seven images is showing up. And if I click on a pagination link the url shows my that I clicked on a pagination link but that's all. If I click for example vife times on a next or previous link the url can show my this;http://www.robcnossen.nl/view_album.php?album_id=8?page=2?page=2?page=0?page=2?page=0
The site is http://www.robcnossen.nl/view_album.php?album_id=8
I hope you can see what causes the problem.
Thanks...
If I were you I would either download a working solution from the net and adapt it to your particular situation OR refactor the whole thing taking into consideration some SoC (Separation of Concerns).
Separate your concerns, leave the logic out of the presentation
Separate the the pagination logic from the rest. Pagination should only need to know at most 4 things to show its links
the target URL: the links need a homogeneous url scheme, only a pageNum in the url will change
how many links have to show up (probably an array of pageNums containing the variable part)
[optional] the current ID being viewed, probably to blur out a page
[optional] logic behind first/last, and behind prev/next
Help yourself by cleaning up your code and also encapsulating some functionality. For example:
function html_a($href, $content) {
return ''.$content.'';
}
function pag_href($url, $id) {
return sprintf($url,$id);// url: host/target.php?pageNum=%s&someOtherstuff...
}
// usage inside loop
echo html_a(pag_href($url,$id),$pageNum);
// if you do this right, your pagination code can become reusable
use some mysql features to your advantage. You can limit the number of results with LIMIT, set the first element of the page with OFFSET, and still get the total of number of rows with SQL_CALC_FOUND_ROWS
// This way is clearer for me
$q = 'SELECT SQL_CALC_FOUND_ROWS image_id FROM images WHERE album_id=? ORDER BY image_id DESC LIMIT ? OFFSET ?'
// after executing your query you may now use pdo's foundRows
$totalNumEntries = $pdo->foundRows();
// get number of pages with pageSize
$totalNumPages = (int)ceil($totalNumEntries / $yourPageSize);
All in all, try to practice some encapsulation/separation of concerns, do some planning ahead and you won't have to deal with code that not even you want to debug
I'm sorry this does not help with your existing code

Categories