php - shuffle : Display only one row at the same time

790

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks

<?php                             
 $sql = "SELECT id,name  FROM table ";
 $rows = array();
 $result = $objCon->query($sql);    
  while($row = $result->fetch_assoc())
   {                      
   $rows[] = $row;
   }                                     
 shuffle($rows);  
 echo '<ol>';
 foreach($rows as $row)
   {
   echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
   }

 echo '</ol>';                         

?>
341

Answer

Solution:

Change your SQL request:

SELECT id,name FROM table ORDER BY RAND() LIMIT 1;

193

Answer

Solution:

You can do it using PHP:

....
shuffle($rows);  
$randomRow = reset($rows);

....

But the better way is to change your SQL query:

$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
126

Answer

Solution:

<?php
    $sql = "
    SELECT id, name  
    FROM table
    ORDER BY RAND()
    LIMIT 1 ";
    $result = mysql_query($sql); 

    // As you are only return a single row you do you require the while()   
    $row = mysql_fetch_array($result);

    echo '<ol>';
      echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
    echo '</ol>';
?>

By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.

The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

People are also looking for solutions to the problem: php - Duplication visibility attributes Doctrine/Symfony

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.