Hi people as a new web programming im having a scenario and i need some help.
Im trying to have a 'next' button on the page which will pull the next question from the database in a iterative manner. im passing php values straight to the button as text.
Currently I can grab the mysql resultset and print them all or i can grab just the one row and return its fields but what is the strategy to grab one with the next button, then another, and so on.
$result = mysql_query("SELECT * FROM $DB_QUEST_NAME ORDER BY pk_Id DESC;") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo $pk_id = $row[0] . "<br>";
echo $question = $row[1]. "<br>";
echo $answera = $row[2] . "<br>";
echo $answerb = $row[3] . "<br>";
echo $answerc = $row[4] . "<br>";
echo $answerd = $row[5] . "<br><br>";
break;
}
In the mark up include the getNextPoll.php (above) which initial grabs the first result to displays them as button. but with every subsequent click I want to get the next, then the next and so on. I know how to set the button texts and Im also aware of server side client side responsibilites but as Im quite new to this type of development the methodology behind it a lil tricky.
Any feedback would be appreciated. Thanks.
I believe you're looking for MySQL's "offset". This allows you to run a query like ... limit 1 offset 0
to return the first result, then ... limit 1 offset 1
to return the 2nd result...and so on.
(You don't really need "offset 0", since that's the default anyway, but - just trying to illustrate the point.)
EDIT:
If you store the page variable in the URL like this: www.myPage.com/questions.php?pg=2
Then you can do this:
$numPerPage = 1;
$pg = $_GET['pg'];
$nxtPage = $pg++;
$offset = ($numPerPage * $pg) - 1;
$question = mysql_query("SELECT * FROM questions LIMIT " . $numPerPage .
" OFFSET " . $offset);
Then, you're "next" link could be:
<a href="questions.php?pg=<?=$nxtPage?>">NEXT</a>
Use "Offset" and "Limit" in the query. Check: http://www.petefreitag.com/item/451.cfm for a simple example.
Your $DB_QUEST_NAME
table should also have an ord
column where you set your questions order (I won't base it on primary key: what if you want to later add a new question as the first one?)
Then next
button should query for $ord + 1
(if any).
You can use LIMIT for your query
Example getting first 10 results:
"SELECT * FROM $DB_QUEST_NAME ORDER BY pk_Id DESC LIMIT 1,10";
To get next just multiply by the page number:
$page_number = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 10;
$end = $results_per_page * $page_number;
start = $end - $results_per_page;
"SELECT * FROM $DB_QUEST_NAME ORDER BY pk_Id DESC LIMIT {$start},{$end}";
This is just a basic example. For a real implementation, use offset, as others have explained