Jump to content

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


dangar

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>
			
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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.