[WTB] PHP random row from database

Discussion in 'Programming' started by almondj, Jun 7, 2008.

  1. #1
    NVM, I got it. Here's what I did in case anyone else wants it.

     <?php
    
    // Create the connection and select the DB
    $link = mysql_connect("localhost","username","password");
    
    if ($link) {
       mysql_selectdb("database",$link);
    
       // Select records from the DB
       $query  = "SELECT * FROM login ORDER BY Rand() LIMIT 1";
       $result = mysql_query($query);
    
       // Display records from the table
       echo "<table border='1'>";
       while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
          echo "<table><tr><td>$row[4]</td></tr></table>";
       }
       echo "</table>";
    } else {
        echo "Can't connect to the database!";
    }
    
    ?>
    PHP:
    Full code^.

    <?php
    
    // Create the connection and select the DB
    $link = mysql_connect("localhost","username","password");
    
    if ($link) {
       mysql_selectdb("database",$link);
    PHP:
    This piece is the beginning that needs to be edited by you. Edit: "localhost," "username," "password," and "database." These should be available from your hoster.

       // Select records from the DB
       $query  = "SELECT * FROM login ORDER BY Rand() LIMIT 1";
       $result = mysql_query($query);
    PHP:
    The "*" queries whichever row that is defined in the echo part. LIMIT 1 defines how many results to show at once, in this case one.

       // Display records from the table
       echo "<table border='1'>";
       while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
          echo "<table><tr><td>$row[4]</td></tr></table>";
       }
       echo "</table>";
    
    PHP:
    This is where the action goes on :). "<td>$row[4]</td> will display a random variable from whatever $row[4] is in the desired table of the database. In this case it is "login." $row[5] could be another variable to. For example, in your database $row[3] is named "url" when the echo has $row[3] and the page is refreshed, it will show a random url from row 3.
     
    almondj, Jun 7, 2008 IP