Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jul 2008
    Location
    Blackpool, UK
    Posts
    176
    Thanks
    4
    Thanked 0 Times in 0 Posts

    RAND() Function QUERY Help

    Hi guys,



    I have this bit of code which is just pulling an ID from the database and listing them on the page.


    What I wanted to do was pull out one ID at random, but as I am new to PHP was wondering how I would do this.

    PHP Code:
    <?PHP


    mysql_select_db
    ("$database"$dbh);

    $result mysql_query("SELECT * FROM portfolio ORDER BY id");

    while(
    $row mysql_fetch_array($result))
      {
      echo 
    $row['id'];
      echo 
    "<br />";
      
      
      
     }
    mysql_close($dbh);
    ?>

    I tried the RAND() function but I don't think I coded it right.


    Any help would be great, as the next part in my project is to pull out

    info at random from database from 3 of the colmns in my table.


    cheers

  • #2
    teh Moderatorinator
    Join Date
    Sep 2004
    Location
    USA
    Posts
    2,472
    Thanks
    4
    Thanked 40 Times in 40 Posts
    Add it to the order by in your query:
    SELECT * FROM table ORDER BY RAND() LIMIT 1;

    Good luck;

  • #3
    Regular Coder
    Join Date
    Jul 2008
    Location
    Blackpool, UK
    Posts
    176
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Hi Brandoe


    Just after I posted I did a bit of research on W3schools and manged to create the random thing great.


    Thanks for your input tho

  • #4
    Regular Coder
    Join Date
    May 2008
    Location
    Ohio
    Posts
    231
    Thanks
    3
    Thanked 21 Times in 21 Posts
    What is your application and how many rows do you expect to have? It makes me cringe when I see "ORDER BY RAND()" and a "LIMIT" in the same query. If you've got a lot of rows, mysql is going to generate a random number for each one of them - an expensive operation. Then it's got to go and find the lowest one of them - also expensive. I'm sure there are a number of threads in the mysql forum about this, but just in case have a read: http://www.titov.net/2005/09/21/do-n...ws-from-table/
    zok@zoklet:~$ whereis zok
    zok: http://zoklet.net | http://zoklet.net/otg | /derzok/at/gmail/dot/com


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •