Jump to content

Checking for available rows while navigating to next or previous element in the database


dangar
Go to solution Solved by ginerjm,

Recommended Posts

I have used the following code to provide a link to view next and previous image fetching from the database. After successfully navigating through all the elements the link will break as it will look for the next row element which is not there. How can I make it to check if the row is available first and then return the result. 

 

<?php 
				
				$id = $_GET['id'];
				$prevquery= mysqli_query($conn, "select * from products where PRODUCT_ID < $id order by PRODUCT_ID desc limit 1");
				while($row2 = mysqli_fetch_array($prevquery))
				{
					$previd = $row2['PRODUCT_ID'];
				}
				
				$nextquery= mysqli_query($conn, "select * from products where PRODUCT_ID > $id order by PRODUCT_ID asc limit 1");
				while($row2 = mysqli_fetch_array($nextquery))
				{
					$nextid = $row2['PRODUCT_ID'];
				}
				
			?>

			 <a href = "Productdetails.php?id=<?php echo $previd?> "> Previous</a>";

			<a href = "Productdetails.php?id=<?php echo $nextid; ?>"> Next</a>
			
Edited by dangar
Link to comment
Share on other sites

A couple things:

 

1. Don't query "SELECT *". Just query the fields you need, in this case the 'PRODUCT_ID'. Using '*' is, at best, inefficient and, at worst, can open a security vulnerability.

 

2.

 

. . .  the link will break as it will look for the next row element which is not there.

You should still build logic to prevent the link from "breaking", e.g. a friendly message that the image could not be found. An image could be deleted before the user clicks the next link, the user may bookmark a page, etc.

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.