Jump to content

Get random row from database by php?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Ahmos

Ahmos

    Newbie

  • Members
  • PipPip
  • 12 posts
this is the first connect between database and Php
by running it am not get any result :(

<?

function randomcourse()

           {

			   $dbName = 'tester';

    $dbUser = 'root';

    $dbPass = '123456';

    $dbServer = 'localhost';


    $conn = mysql_connect( $dbServer , $dbUser , $dbPass );

    if( !conn )

    {

        echo "can not make any connection";

        exit;

    }

    $select = mysql_select_db( $dbName );

    if( !$select )

    {

        echo "can not find the database";

        exit;

    }

			  $query = "SELECT co_id FROM course ";

			   $result = mysql_query($query);

			   $num = mysql_num_rows($result);

			   if ($num > 0) 

			         {

					 $id_array = array();

				        while ($row = mysql_fetch_assoc($result))

                                              {

                                                       $id_array []=$row['co_id'];                

                                             }

						  

				      $query = "SELECT * FROM course WHERE 'co_id'=".$id_array[rand(0, (count($id_array)-1))];

				    $result = mysql_query($query);

				

				

				while($row = mysql_fetch_array($result))

				      {

				echo $row["co_id"];

               echo $row["co_name"];

                echo $row["co_des"];

				      }

		  }}

		  randomcourse();

?>
so what can I do to solve this ?:cursing:

#2
Revolt

Revolt

    Programmer

  • Members
  • PipPipPip
  • 99 posts
You could accomplish this directly with the MySQL query which would also be faster:

SELECT column FROM table

ORDER BY RAND()

LIMIT 1

for similar queries in other engines you can check:
SQL to Select a random row from a database table

#3
Ahmos

Ahmos

    Newbie

  • Members
  • PipPip
  • 12 posts
thanks :)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users