Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
  • Register
Welcome to the Q&A for Question2Answer.

If you have questions about the platform, click here to ask and please use English.

If you just want to try Q2A, please use the demo, which also grants admin access.

Apr 29: Q2A 1.5.2

How can i get random question from database ?

+3 votes
Not really good at PHP/Mysql can someone can help ?
asked Aug 22, 2011 in Q2A Core by Another one
that is strange... must be a database thing - can you tell me what the collation is for your posts table?
MySQL connection collation: utf8_general_ci. This is global i think.

MySQL charset: UTF-8 Unicode (utf8) (from another place)

1 Answer

0 votes

What a neat idea... would make for a good plugin :)  This works (tested):

            $random_question = qa_db_read_one_assoc(
                qa_db_query_sub(
                    'SELECT * FROM ^posts WHERE type=$ ORDER BY rand() LIMIT 1',
                    'Q'
                ),
                true
            );

It returns an array of one question.

answered Aug 29, 2011 by NoahY
I tried:
            $rand = qa_db_read_one_value(
                qa_db_query_sub(
                    'SELECT MAX(postid) FROM ^posts'
                ),
                true
            );
            if(!$rand) return;
            $rand = rand()/getrandmax()*$rand;
            $random_question = qa_db_read_one_assoc(
                qa_db_query_sub(
                    'SELECT * FROM ^posts WHERE type=$ AND postid >= # LIMIT 1',
                    'Q',$rand
                ),
                true
            );

and it takes the same time as the above query, maybe a bit longer... I guess this way will be quicker with larger databases?
Thank you! I'm using your plugin! Can I do this: Place of picking different questions, change the Unanswered Questions or Problems with the Best answer!