[PHP-DB] Re: Random question selection in PHP w/ MySQL backend. From: Hugh Bothwell (hugh_bothwell <email protected>)
Date: 07/31/01

> "Adam Lundrigan" <ceo <email protected>> wrote in message
> news:20010731203402.13490.qmail <email protected>
> What i need to do is select 10 questions from a database
> (db: vpt, table: questions), and make sure that the same
> question doesn't appear twice. The questions need to
> appear in a random order each time the script is loaded.

$mysql_connect("host", "user", "pwd");

$result = $mysql_db_query("vpt",
    "SELECT id, txt FROM questions "
    ."ORDER BY RANDOM() LIMIT 10"
);

    function makeQuestion($qid) {
        return (
             "<input type='radio' name='q[$qid]' value=1>1"
            ."<input type='radio' name='q[$qid]' value=2>2"
            ."<input type='radio' name='q[$qid]' value=3>3"
            ."<input type='radio' name='q[$qid]' value=4>4"
            ."<input type='radio' name='q[$qid]' value=5>5"
        );
    }

    function makeRow() {
        $str = "\n\t<tr>";

        $num = func_num_args();
        for ($i = 0; $i < $num; $i++)
            $str .= "\n\t\t<td>".func_get_arg($i)."</td>";

        $str .= "\n\t</tr>";
        return $str;
    }

echo "\n<form>\n<table>";

while ($row = mysql_fetch_array($result))
    echo makeRow(makeQuestion($row[id]), $row[txt]);

echo makeRow("<input type='reset'>", "<input type='submit'>");
echo "\n</table>\n</form>";

Voila - they get ten questions at random, in random order;
 when they submit the form, you get the question id back as
the array key and the answer as the value.

Hope that helps ;-)

-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, e-mail: php-db-unsubscribe <email protected>
For additional commands, e-mail: php-db-help <email protected>
To contact the list administrators, e-mail: php-list-admin <email protected>