Dear all,

In mysql, I would like to select one row of date from the table "TEST" in random. Please give me some help, thanks

Regards,
Simon

    Just create your query, and use a random variable number created by php.

    <?php
    $rand = rand(1, 5);
    
    $query = "SELECT * FROM `TABLES` WHERE id = '".$rand."' LIMIT 1";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    ?>

    int rand ( [int min, int max] )
    Example 1. rand() example

    <?php
    echo rand() . "\n";
    echo rand() . "\n";
    
    echo rand(5, 15);
    ?> 

    The above example will output something similar to:

    7771
    22264
    11

    PHP Manual - rand()

    Hope that helps.

    ~Brett

      If two rows of data are taken instead of one row, how does it do?

      Thanks
      Simon

        You would have to execute the query twice, calling a function to get another random number.

        ~Brett

          SELECT * FROM table ORDER BY RAND() LIMIT 1

            Dears,

            I try it, but such query is not good, since the id's may not be continuous, resulting in no data some time. So please help me with any other solutions. Also if I want the random no be the same for a whole day, how does it do?

            Thanks for any of your help.

            Simon

              If you want a random record for the day, choose the record in the same manner and then store the id in a record or file.

              Your script could check for the existance of the stored id and whether it's time to get a new random id to store (you could put the id in a record that is timestamped for example.)

                10 months later
                apcmlee wrote:

                Dears,

                I try it, but such query is not good, since the id's may not be continuous, resulting in no data some time. So please help me with any other solutions. Also if I want the random no be the same for a whole day, how does it do?

                Thanks for any of your help.

                Simon

                Hi,
                I think this what ur trying to do, try this out.. 🙂

                
                <?php
                $limited = 10;
                $rand = rand(1, $limited);
                
                $query = "SELECT * FROM `TABLES` LIMIT ".$rand.", " . $limited;
                $result = mysql_query($query);
                $row = mysql_fetch_array($result);
                ?> 
                
                
                  Write a Reply...