Display Next result On click in PHP

When I think about online test module or project in PHP during my study Life, then a very important point arise in my mind how to get next or previous question in PHP without using JavaScript. Now a day, working as web developer I attempt and feel that it is very easy snippet to do so. In this article, we are going to discuss how to fetch row on click of next button in PHP. You will see how it is easy to attempt so.Let us see tutorial.

resultonclick - PHPCluster
resultonclick – PHPCluster

DB Config:
Database : onlinetest
Table : Question
PHP

<?php
mysql_connect("localhost","root","");
mysql_select_db("onlinetest");

if(isset($_POST['qid'])){

$qid=$_POST['qid'];
}
elseif(isset($_POST['pid']))
{
$qid=$_POST['pid'];
}
else
{
$qid=1;
}
$no=mysql_num_rows(mysql_query("SELECT * FROM `question`"));

$sql=mysql_query("SELECT * FROM `question` WHERE `id`='$qid'");
$limit=mysql_num_rows($sql);
while($rows=mysql_fetch_array($sql))
{?>
<?php echo "Question".$rows['id']." "."<b>".$rows['ques']."</b>"; ?>
<?php  $lid= $rows['id']; ?>

<?php } ?>
<table>
<tr>
<td>
<?php if($lid>1){?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="pid" value="<?php echo $pid= $lid-1; ?>">
<input type="submit" name="next" value="Previous">
</form><?php } ?>
</td><td>
<?php if($lid<$no){ ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="qid" value="<?php echo $lid= $lid+1; ?>">
<input type="submit" name="next" value="Next">
</form><?php } ?>
</td>
</tr></table>

Here we are using two form for previous and next button to fetch their corresponding rows from database. If we click on previous button then send $id-1 than current id and for next button sending $id+1 ID to get next tuple. In this approach we no need to use any Javascript snippet.
Very simple approach to display next and previous row from database. That’s it.

Leave a Comment