简体   繁体   中英

Select unseen random row from MySQL table

We have a list of questions in a MySQL database and want it to show a random approved question to the user. When you click the Random button, we want another random question to be shown, but not any of the ones the user has already seen.

Right now the script looks like this:

<?php

mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("aldrig") or die(mysql_error());

$result = mysql_query("SELECT * FROM spg WHERE approved='1' ORDER BY RAND() LIMIT 1;") 
or die(mysql_error());    

while($row = mysql_fetch_array( $result )) {
    echo "<div class='contentTitle'><h1>";
    echo $row['text']; 
    echo "</h1></div>";
}

?>

I suggest you fetch all the questions, and instead in your code work out which once have already been shown by taking them out of the result list and into a new list if you don't want to throw them away.

    <?php

mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("aldrig") or die(mysql_error());

$result = mysql_query("SELECT * FROM spg WHERE approved='1'") or die(mysql_error());
$answers = mysql_fetch_array($result);

start_session();

if (isset($_COOKIE["answers"]))
    $alreadyShownAnswers = json_decode($_COOKIE["answers"]);
else
    $alreadyShownAnswers = array();

$answerToShow = $answers[$randomIndex];
$alreadyShownAnswers[] = $answers[$randomIndex];
unset($answers[$randomIndex]);
$answers = array_values($answers);

echo "<div class='contentTitle'><h1>";
echo $answerToShow; 
echo "</h1></div>";

$_COOKIE["answers"] = json_encode(alreadyShownAnswers);

?>

something like this maybe?

The way to do it with cookie or session

start_session();
$_COOKIE["answer1"] = $answer1;
$_SESSION["answer2"] = $answer2;

now when you want to retrieve these values again after resreshing do this.

start_session();
$answer1 = $_COOKIE["answer1"];
$answer2 = $_SESSION["answer2"];

to use JavaScript for persistent storage use lawnchair: http://brian.io/lawnchair/

example:

var store = new lawnchair({name:'testing'}, function(store) {

    // create an object
    var me = {key:'brian'};

    // save it
    store.save(me);

    // access it later... yes even after a page refresh!
    store.get('brian', function(me) {
        console.log(me);
    });
});

Updated the first code block with the new code, i have not tested this but something like that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM