Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Display a random entry from a MySQL database in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 109
    Comment on it

    To display a random entry from a MySQL database we need to use a MySQL function rand(). To display the entry from MySQL database in PHP following script is used:

    <?php
    //connect to server with username and password,
    $connection = mysql_connect ("localhost","root", "root") or die ("Cannot make the connection");
    //connect to database
    $db = mysql_select_db ("demo",$connection) or die ("Cannot connect to database");
    //our SQL query
    $sql_query = "SELECT * FROM test ORDER BY RAND() LIMIT 1";
    //store the SQL query in the result variable
    $result = mysql_query($sql_query);
    if(mysql_num_rows($result))
    {
    //output as long as there are still available fields
    while($row = mysql_fetch_row($result))
    {
    print_r($row);
    }
    }
    //if no fields exist
    else
    {
    echo "no values in the database";
    }
    
    ?>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: