savagenoob Posted April 25, 2009 Share Posted April 25, 2009 I am using MySQL to return a random row but it loops through and I was wondering of a way to not return a row that has already been displayed. Its a quiz program and the user selects the number of questions they want displayed and the code loops through that many rows. $select = "SELECT * FROM pq_crtp_quiz WHERE testname = '$testname' ORDER BY RAND() DESC LIMIT 1"; Quote Link to comment https://forums.phpfreaks.com/topic/155593-random-row/ Share on other sites More sharing options...
Maq Posted April 25, 2009 Share Posted April 25, 2009 Your query is only returning 1 row, so we would need to see the surrounding code where it loops. You may be able to just use DISTINCT rather then a loop. Again, we would need to see some more code. Quote Link to comment https://forums.phpfreaks.com/topic/155593-random-row/#findComment-818880 Share on other sites More sharing options...
Daniel0 Posted April 25, 2009 Share Posted April 25, 2009 Can't you just set the LIMIT in the query to the number of rows the user asked for? Quote Link to comment https://forums.phpfreaks.com/topic/155593-random-row/#findComment-818895 Share on other sites More sharing options...
savagenoob Posted April 25, 2009 Author Share Posted April 25, 2009 No because the page refreshes each time the user submits the answer to a question. I think I have to store the question numbers already called in a table in the database and cross reference it each page submit. Might work. Quote Link to comment https://forums.phpfreaks.com/topic/155593-random-row/#findComment-818901 Share on other sites More sharing options...
Daniel0 Posted April 25, 2009 Share Posted April 25, 2009 Then something like this perhaps (assuming id is the primary key): session_start(); if (!isset($_SESSION['selected'] || !$in = join(',', $_SESSION['selected'])) { $in = null; } else { $in = ' AND id NOT IN (' . $in . ')'; } $res = mysql_query("SELECT * FROM pq_crtp_quiz WHERE testname = '{$testname}'{$in} ORDER BY RAND() DESC LIMIT 1"); $row = mysql_fetch_assoc($res); $_SESSION['selected'][] = $row['id']; Quote Link to comment https://forums.phpfreaks.com/topic/155593-random-row/#findComment-818908 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.